Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5 Output: 7 Explanation: Choosing one element from each row, the first k smallest sum are: [1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
Example 2:
Input: mat = [[1,3,11],[2,4,6]], k = 9 Output: 17
Example 3:
Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7 Output: 9 Explanation: Choosing one element from each row, the first k smallest sum are: [1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.
Constraints:
m == mat.lengthn == mat.length[i]1 <= m, n <= 401 <= mat[i][j] <= 50001 <= k <= min(200, nm)mat[i] is a non-decreasing array.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
[[1,3,11],[2,4,6]] 5
[[1,3,11],[2,4,6]] 9
[[1,10,10],[1,4,5],[2,3,6]] 7
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1439: Find the Kth Smallest Sum of a Matrix With Sorted Rows
class Solution {
public int kthSmallest(int[][] mat, int k) {
int m = mat.length, n = mat[0].length;
List<Integer> pre = new ArrayList<>(k);
List<Integer> cur = new ArrayList<>(n * k);
pre.add(0);
for (int[] row : mat) {
cur.clear();
for (int a : pre) {
for (int b : row) {
cur.add(a + b);
}
}
Collections.sort(cur);
pre.clear();
for (int i = 0; i < Math.min(k, cur.size()); ++i) {
pre.add(cur.get(i));
}
}
return pre.get(k - 1);
}
}
// Accepted solution for LeetCode #1439: Find the Kth Smallest Sum of a Matrix With Sorted Rows
func kthSmallest(mat [][]int, k int) int {
pre := []int{0}
for _, row := range mat {
cur := []int{}
for _, a := range pre {
for _, b := range row {
cur = append(cur, a+b)
}
}
sort.Ints(cur)
pre = cur[:min(k, len(cur))]
}
return pre[k-1]
}
# Accepted solution for LeetCode #1439: Find the Kth Smallest Sum of a Matrix With Sorted Rows
class Solution:
def kthSmallest(self, mat: List[List[int]], k: int) -> int:
pre = [0]
for cur in mat:
pre = sorted(a + b for a in pre for b in cur[:k])[:k]
return pre[-1]
// Accepted solution for LeetCode #1439: Find the Kth Smallest Sum of a Matrix With Sorted Rows
struct Solution;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashSet;
impl Solution {
fn kth_smallest(mat: Vec<Vec<i32>>, mut k: i32) -> i32 {
let n = mat.len();
let m = mat[0].len();
let mut queue: BinaryHeap<(Reverse<i32>, Vec<usize>)> = BinaryHeap::new();
let mut visited: HashSet<Vec<usize>> = HashSet::new();
let mut sum = 0;
let indexes = vec![0; n];
for i in 0..n {
sum += mat[i][0];
}
visited.insert(indexes.to_vec());
queue.push((Reverse(sum), indexes));
let mut res = 0;
while k > 0 {
if let Some((Reverse(sum), indexes)) = queue.pop() {
res = sum;
for i in 0..n {
let mut next_sum = sum;
let mut next_indexes = indexes.to_vec();
let j = indexes[i];
if j + 1 < m {
next_indexes[i] = j + 1;
if visited.insert(next_indexes.to_vec()) {
next_sum -= mat[i][j];
next_sum += mat[i][j + 1];
queue.push((Reverse(next_sum), next_indexes));
}
}
}
}
k -= 1;
}
res
}
}
#[test]
fn test() {
let mat = vec_vec_i32![[1, 3, 11], [2, 4, 6]];
let k = 5;
let res = 7;
assert_eq!(Solution::kth_smallest(mat, k), res);
let mat = vec_vec_i32![[1, 3, 11], [2, 4, 6]];
let k = 9;
let res = 17;
assert_eq!(Solution::kth_smallest(mat, k), res);
let mat = vec_vec_i32![[1, 10, 10], [1, 4, 5], [2, 3, 6]];
let k = 7;
let res = 9;
assert_eq!(Solution::kth_smallest(mat, k), res);
let mat = vec_vec_i32![[1, 1, 10], [2, 2, 9]];
let k = 7;
let res = 12;
assert_eq!(Solution::kth_smallest(mat, k), res);
}
// Accepted solution for LeetCode #1439: Find the Kth Smallest Sum of a Matrix With Sorted Rows
function kthSmallest(mat: number[][], k: number): number {
let pre: number[] = [0];
for (const cur of mat) {
const next: number[] = [];
for (const a of pre) {
for (const b of cur) {
next.push(a + b);
}
}
pre = next.sort((a, b) => a - b).slice(0, k);
}
return pre[k - 1];
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.