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
Find Kth Smallest Sum: Choose One From Each RowInput Matrix:1311246All Possible Arrays:[1,2] → sum = 3[1,4] → sum = 5[1,6] → sum = 7[3,2] → sum = 5[3,4] → sum = 7[3,6] → sum = 9[11,2] → sum = 13[11,4] → sum = 15[11,6] → sum = 17Sorted Sums: [3, 5, 5, 7, 7, 9, 13, 15, 17]For k = 5:5th smallest = 7
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
Asked in
Google 15 Facebook 12 Amazon 8
18.5K Views
Medium Frequency
~35 min Avg. Time
780 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen