Skip to main content
Back to problems
#1439
Hard Algorithms

Find the kth smallest sum of a matrix with sorted rows

Array Binary Search Heap (Priority Queue) Matrix
62.3% acceptance
Feb 25, 2026
1292
21
You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k. You are allowed to choose exactly one element from each row to form an array. Return the kth smallest array sum among all possible arrays.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn kth_smallest(mat: Vec<Vec<i32>>, k: i32) -> i32 {
    let k = k as usize;
    let mut sums: Vec<i32> = mat[0].clone();
    for row in &mat[1..] {
      let mut new_sums = vec![];
      for &s in &sums {
        for &e in row {
          new_sums.push(s + e);
        }
      }
      new_sums.sort_unstable();
      new_sums.truncate(k);
      sums = new_sums;
    }
    sums[k - 1]
  }
}