The K Weakest Rows in a Matrix

EasyBinary Searchbinary search

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You get an m x n binary matrix mat. In each row, every 1 (a soldier) comes before every 0 (a civilian). Row i is weaker than row j if it has fewer soldiers, or if both have the same number of soldiers and i < j. Return the indices of the k weakest rows, ordered from weakest to strongest. Counting soldiers with binary search gives O(m log n + m log m).

Examples

Input: mat = [[1,1,0,0],[1,0,0,0],[1,1,1,1],[1,0,0,0]], k = 2
Output: [1,3]
Soldier counts are 2, 1, 4, 1. Rows 1 and 3 both have one soldier; row 1 comes first by index.
Input: mat = [[1,1,1],[0,0,0],[1,1,0]], k = 3
Output: [1,2,0]
Counts are 3, 0, 2, so the order is row 1, row 2, row 0.

Constraints

  • m == mat.length, n == mat[i].length
  • 1 <= m, n <= 100
  • 1 <= k <= m
  • `mat[i][j]` is 0 or 1, and all 1s precede all 0s in each row.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More binary search problems