The K Weakest Rows in a Matrix (LeetCode 1337): Solution and Explanation

Easy
Array
Binary search
Sorting
Heap (priority queue)
Matrix

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

  1. For each row i, binary search with lo = 0, hi = n for the first 0. When the loop ends, lo is the soldier count.
  2. Push (soldiers, i) onto a max-heap ordered by soldiers, then by index.
  3. If the heap holds more than k rows, pop its top (the strongest).
  4. 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
  1. Row 0: binary search finds the first 0 at index 2, so 2 soldiers. Heap: {(2,0)}.
  2. Row 1: 4 soldiers. Heap: {(4,1), (2,0)}.
  3. Row 2: 1 soldier. Heap: {(4,1), (2,0), (1,2)}, size 3 = k.
  4. Row 3: 2 soldiers. Push makes size 4, so pop the top (4,1). Heap: {(2,3), (2,0), (1,2)}.
  5. 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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.