Leetcode 1337. The K Weakest Rows in a Matrix
You are given an m x n
binary matrix mat
of 1
’s (representing soldiers) and 0
’s (representing civilians). The soldiers are positioned in front of the civilians in each row, that is, all the 1’s will appear to the left of all the 0’s in each row.
A row i
is weaker than a row j
if one of the following is true:
i
is less than the number of soldiers in row j
.i
is less than j
.Return the indices of the k
weakest rows in the matrix ordered from weakest to strongest.
k
is greater than the number of rows? Assume that k
will be valid and less than or equal to the number of rows.To solve this problem:
k
elements from the sorted vector.k
indices will take (O(k)) time.Overall, the time complexity will be (O(m \cdot n + m \log m + k)).
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
int m = mat.size();
vector<pair<int, int>> soldierCount(m);
// Count the number of soldiers in each row
for (int i = 0; i < m; ++i) {
int count = countSoldiers(mat[i]);
soldierCount[i] = {count, i};
}
// Sort by number of soldiers and then by row index
sort(soldierCount.begin(), soldierCount.end());
// Extract the first k indices
vector<int> result;
for (int i = 0; i < k; ++i) {
result.push_back(soldierCount[i].second);
}
return result;
}
private:
int countSoldiers(const vector<int>& row) {
int low = 0, high = row.size();
while (low < high) {
int mid = (low + high) / 2;
if (row[mid] == 1) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
};
kWeakestRows
: This is the main function that calculates the k weakest rows.
m
.soldierCount
where each pair contains the number of soldiers and the row index.countSoldiers
.soldierCount
.k
weakest rows from the sorted vector.countSoldiers
: This helper function computes the number of soldiers in a given row using binary search.
1
s in a sorted row of 1
s followed by 0
s.This approach ensures an efficient solution to the problem with balanced time complexity considerations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?