The K Weakest Rows in a Matrix

Rank rows by (soldiers, index) and return the k weakest — binary search soldier counts plus a heap.

Easy
Time O(m * (log n + log k)) Space O(k)
LeetCode
7 min read
binary-search heaps

Problem#

Each row of the binary matrix has all 1s before all 0s. The “strength” of a row is the count of 1s. Return the indices of the k weakest rows (ties broken by smaller index).

Examples#

  • mat = [[1,1,0,0,0],[1,1,1,1,0],[1,0,0,0,0],[1,1,0,0,0],[1,1,1,1,1]], k = 3[2,0,3]

Constraints#

  • 2 <= n, m <= 100.

Approach#

Each row’s soldier count is found by binary search (find first 0). Max-heap of (count, index) size k.

Solution#

K Weakest Rows
class Solution {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
priority_queue<pair<int,int>> pq;
for (int i = 0; i < (int)mat.size(); ++i) {
int cnt = lower_bound(mat[i].begin(), mat[i].end(), 0, greater<int>()) - mat[i].begin();
pq.push({cnt, i});
if ((int)pq.size() > k) pq.pop();
}
vector<pair<int,int>> kept;
while (!pq.empty()) { kept.push_back(pq.top()); pq.pop(); }
sort(kept.begin(), kept.end());
vector<int> ans;
for (auto& [c, i] : kept) ans.push_back(i);
return ans;
}
};

Editorial#

Binary search per row (sorted descending wrt 1s-before-0s) gives the soldier count in O(log n). A max-heap of size k keeps the weakest k as we scan, tied to row indices for the tie-breaker.

Complexity#

  • Time: O(m * (log n + log k)).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.