Skip to content
Decoder

The K Weakest Rows in a Matrix

Easy

Problem

A grid mat describes an army: 1 is a soldier and 0 is a civilian. In every row, all the soldiers stand before all the civilians (the 1s come first).

Row i is weaker than row j if it has fewer soldiers, or the same number of soldiers and i < j. Return the indices of the `k` weakest rows, weakest first.

Example 1

mat = [[1,1,0,0,0],

Example 2

       [1,1,1,1,0],

Example 3

       [1,0,0,0,0],

Example 4

       [1,1,0,0,0],

Example 5

Input
[1,1,1,1,1]], k = 3
Output
[2, 0, 3]

Soldier counts are 2, 4, 1, 2, 5. Row 2 is weakest, then rows 0 and 3 (tied at 2, so the smaller index first).

Constraints

  • 2 <= m, n <= 100 (m rows, n columns)
  • 1 <= k <= m
  • mat[i][j] is 0 or 1.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.