K Weakest Rows in Matrix

Given a binary matrix where each row is sorted with soldiers first and then civilians, return the indices of the k weakest rows. A row is weaker if it has fewer soldiers; ties are broken by smaller row index.

Input Format

mat = binary matrix, k = number of weakest rows to return

Output Format

row indices of the k weakest rows sorted by weakness and then index

Constraints

  • 1 <= mat.length, mat[i].length <= 100
  • mat[i][j] is 0 or 1
  • rows are sorted with all 1s before 0s

Examples

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:

Row 2 has 1 soldier, rows 0 and 3 have 2 soldiers, and row 0 comes before row 3 on the tie.

Example 2:

Input:

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

Output:

[2,0]

Explanation:

Row 2 is weakest with 0 soldiers, then row 0 with 1 soldier.

Loading...
K Weakest Rows in Matrix - Heap DSA Problem