The K Weakest Rows in a Matrix Problem
Description
LeetCode Problem 1337.
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. 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:
- The number of soldiers in row
iis less than the number of soldiers in rowj. - Both rows have the same number of soldiers and
i < j.
Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.
Example 1:
Input: 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
Output: [2,0,3]
Explanation:
The number of soldiers in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
The rows ordered from weakest to strongest are [2,0,3,1,4].
Example 2:
Input: mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
Output: [0,2]
Explanation:
The number of soldiers in each row is:
- Row 0: 1
- Row 1: 4
- Row 2: 1
- Row 3: 1
The rows ordered from weakest to strongest are [0,2,3,1].
Constraints:
m == mat.lengthn == mat[i].length2 <= n, m <= 1001 <= k <= mmatrix[i][j]is either 0 or 1.
Solution
Approach: Binary Search + Sorting
A row's strength is its number of soldiers, and because every row is all 1's followed by all 0's, that number is just the index of the first 0. Binary search finds it in O(log n) instead of scanning the row: if row[mid] is 1, the first 0 is to the right of mid; otherwise it is at mid or to its left. A row of only 1's has n soldiers, which the search returns when it runs off the end.
Then sort the row indices by the key (soldiers, index). Including the index in the key gives exactly the tie rule from the statement: rows with the same number of soldiers keep their original order. The first k indices of the sorted list are the answer.
Complexity: O(m log n + m log m) time for the m binary searches and the sort, and O(m) extra space.
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
def soldiers(row: List[int]) -> int:
# The 1's come first, so binary search for the first 0.
lo, hi = 0, len(row)
while lo < hi:
mid = (lo + hi) // 2
if row[mid] == 1:
lo = mid + 1
else:
hi = mid
return lo
count = [soldiers(row) for row in mat]
order = sorted(range(len(mat)), key=lambda i: (count[i], i))
return order[:k]