The K Weakest Rows in a Matrix (LeetCode 1337): Solution and Explanation
Each row of a binary matrix has its soldiers (1s) in front of its civilians (0s). Rank rows by soldier count, breaking ties by index, and return the k weakest rows from weakest to strongest.
Intuition
A row's strength is its number of soldiers. Since every 1 comes before every 0, that number is simply the index of the first 0 in the row.
Finding the first 0 in a sorted row is a textbook binary search: if the middle cell is a soldier, the boundary is to the right; if it is a civilian, the boundary is at mid or to the left.
Once every row has a (soldiers, index) pair, we need the k smallest pairs. A max-heap capped at size k keeps exactly those: whenever it overflows, the strongest row on top is thrown out, because k weaker rows have already been seen.
Approach: Binary search per row + max-heap of size k
- For each row i, binary search with
lo = 0, hi = nfor the first 0. When the loop ends,lois the soldier count. - Push
(soldiers, i)onto a max-heap ordered by soldiers, then by index. - If the heap holds more than k rows, pop its top (the strongest).
- After all rows, pop the heap into a list (strongest first) and reverse it so the weakest row comes first.
Step-by-step example
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
- Row 0: binary search finds the first 0 at index 2, so 2 soldiers. Heap: {(2,0)}.
- Row 1: 4 soldiers. Heap: {(4,1), (2,0)}.
- Row 2: 1 soldier. Heap: {(4,1), (2,0), (1,2)}, size 3 = k.
- Row 3: 2 soldiers. Push makes size 4, so pop the top (4,1). Heap: {(2,3), (2,0), (1,2)}.
- Row 4: 5 soldiers. Push then pop (5,4) right away. Popping the heap gives 3, 0, 2; reversed: [2,0,3].
Code: Python, Java, C++
1class Solution:
2 def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
3 heap = []
4 for i, row in enumerate(mat):
5 lo, hi = 0, len(row)
6 while lo < hi:
7 mid = (lo + hi) // 2
8 if row[mid] == 1:
9 lo = mid + 1
10 else:
11 hi = mid
12 heapq.heappush(heap, (-lo, -i))
13 if len(heap) > k:
14 heapq.heappop(heap)
15 answer = []
16 while heap:
17 answer.append(-heapq.heappop(heap)[1])
18 return answer[::-1]1class Solution {
2 public int[] kWeakestRows(int[][] mat, int k) {
3 PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] != b[0] ? b[0] - a[0] : b[1] - a[1]);
4 for (int i = 0; i < mat.length; i++) {
5 int lo = 0, hi = mat[i].length;
6 while (lo < hi) {
7 int mid = (lo + hi) / 2;
8 if (mat[i][mid] == 1) {
9 lo = mid + 1;
10 } else {
11 hi = mid;
12 }
13 }
14 heap.offer(new int[]{lo, i});
15 if (heap.size() > k) {
16 heap.poll();
17 }
18 }
19 int[] answer = new int[k];
20 for (int j = k - 1; j >= 0; j--) {
21 answer[j] = heap.poll()[1];
22 }
23 return answer;
24 }
25}1class Solution {
2public:
3 vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
4 priority_queue<pair<int, int>> heap;
5 for (int i = 0; i < (int)mat.size(); i++) {
6 int lo = 0, hi = mat[i].size();
7 while (lo < hi) {
8 int mid = (lo + hi) / 2;
9 if (mat[i][mid] == 1) {
10 lo = mid + 1;
11 } else {
12 hi = mid;
13 }
14 }
15 heap.push({lo, i});
16 if ((int)heap.size() > k) {
17 heap.pop();
18 }
19 }
20 vector<int> answer(k);
21 for (int j = k - 1; j >= 0; j--) {
22 answer[j] = heap.top().second;
23 heap.pop();
24 }
25 return answer;
26 }
27};Time and space complexity
O(m log n + m log k)
Each of the m rows takes O(log n) to binary search and O(log k) to push into and maybe pop from the heap.
O(k)
The heap never holds more than k + 1 rows, plus the k-element answer.
Other approaches
Count, then sort (time O(m log n + m log m), space O(m))
Compute every row's soldier count (by binary search or a simple sum), sort the indices by (count, index) and take the first k. Easy to write; O(m log m) for the sort.
Column-by-column scan (time O(m * n), space O(m))
Walk the columns left to right and, in each column, collect the rows that have a 0 there for the first time, in index order. Rows appear exactly in weakest-first order. Stop after k rows.
Common mistakes
- Breaking ties the wrong way. With equal soldiers, the smaller row index is weaker, so the max-heap must treat the larger index as stronger.
- Using a min-heap of all m rows and forgetting the size cap. It works, but uses O(m) space instead of O(k).
- Returning the heap in pop order. A max-heap pops strongest first; reverse it to get weakest first.
- An off-by-one in the binary search. With hi = n (exclusive), an all-soldier row correctly returns n.
Frequently asked questions
Why a max-heap when we want the weakest rows?
We only keep k rows, so the question at each step is which kept row to discard. The strongest kept row is the one to discard, and a max-heap puts it on top.
Is binary search worth it when n is at most 100?
Counting with a sum is fine for these limits. Binary search is the intended trick because the rows are sorted, and it matters when rows are long.
What if a row is all zeros or all ones?
The binary search returns 0 for an all-zero row and n for an all-one row. Both are valid strengths and need no special case.