The K Weakest Rows in a Matrix

You are given an m x n binary matrix mat of 1s (soldiers) and 0s (civilians). In every row, all the soldiers stand in front of the civilians: every 1 appears to the left of every 0. Row i is weaker than row j if row i has fewer soldiers than row j, or they have the same number of soldiers and i < j. Return the indices of the k weakest rows, ordered from weakest to strongest.

30:00

The K Weakest Rows in a Matrix
easy
Free written solution
Topics
Companies

You are given an m x n binary matrix mat of 1s (soldiers) and 0s (civilians). In every row, all the soldiers stand in front of the civilians: every 1 appears to the left of every 0. Row i is weaker than row j if row i has fewer soldiers than row j, or they have the same number of soldiers 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]
Constraints:
  • m==mat.lengthm == \text{mat.length}

  • n==mat[i].lengthn == \text{mat}[i]\text{.length}

  • 2≤n,m≤1002 \leq n, m \leq 100

  • 1≤k≤m1 \leq k \leq m

  • mat[i][j]\text{mat}[i][j] is either 0 or 1.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"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}

5 rows. Soldiers (1) always stand left of civilians (0), so a row's strength is the position of its first 0, which binary search finds fast.

mat

soldiers count = strength

r0

?

r1

?

r2

?

r3

?

r4

?

■ soldier (1)

■ civilian (0)

kept in heap

just evicted

max-heap (size ≤ k = 3)

top = strongest kept

empty

answer (weakest first)

built after every row is counted

Variables
VariableValue
k3
heapSize0
DepthFunction Call
Stack empty
0/27