Skip to main content
Back to problems
#1337
Easy Algorithms

The k weakest rows in a matrix

Array Binary Search Sorting Heap (Priority Queue) Matrix
74.3% acceptance
Feb 25, 2026
4336
242
You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row. A row i is weaker than a row j if one of the following is true: The number of soldiers in row i is less than the number of soldiers in row j. Both rows have the same number of soldiers and i < j. Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn k_weakest_rows(mat: Vec<Vec<i32>>, k: i32) -> Vec<i32> {
    let mut rows: Vec<(i32, usize)> = mat.iter().enumerate()
      .map(|(i, row)| (row.iter().sum::<i32>(), i))
      .collect();
    rows.sort();
    rows.iter().take(k as usize).map(|&(_, i)| i as i32).collect()
  }
}