Find the Kth Smallest Sum of a Matrix With Sorted Rows - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
mat = [[1,3,11],[2,4,6]], k = 5
›
Output:
7
💡 Note:
All possible sums: [3,5,7,5,7,9,13,15,17]. Sorted: [3,5,5,7,7,9,13,15,17]. The 5th smallest is 7.
Example 2 — Small k
$
Input:
mat = [[1,3,11],[2,4,6]], k = 1
›
Output:
3
💡 Note:
The smallest possible sum is choosing the first element from each row: 1 + 2 = 3.
Example 3 — Single Row
$
Input:
mat = [[1,10,10,10,10]], k = 3
›
Output:
10
💡 Note:
Only one row, so we can only choose one element. All sums after the first are 10, so k=3 gives 10.
Constraints
- m == mat.length
- n == mat[i].length
- 1 ≤ m, n ≤ 40
- 1 ≤ mat[i][j] ≤ 5000
- 1 ≤ k ≤ min(200, n^m)
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Each row is sorted in non-decreasing order
2
Generate Arrays
Choose exactly one element from each row
3
Find Kth Sum
Return the kth smallest array sum
Key Takeaway
🎯 Key Insight: Use a min-heap to generate sums in ascending order without creating all combinations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code