#1337
The K Weakest Rows in a Matrix
newbie · 235 · lc easy +18 · verified · 74.3% accepted · 4,336 likes · top 85%
Description
You are given an m x n binary matrix mat where 1 represents a soldier and 0 a civilian, with all soldiers appearing before civilians in each row. Row i is weaker than row j when it has fewer soldiers, or when both rows have the same soldier count and i < j. Return the indices of the k weakest rows 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].
Code
1
2
3