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
Kth Smallest Sum of Matrix With Sorted Rows INPUT Matrix (2x3): 1 3 11 row 0 2 4 6 row 1 k = 5 All Possible Sums: 1+2=3 1+4=5 1+6=7 3+2=5 3+4=7 3+6=9 11+2=13 11+4=15 11+6=17 Sorted: 3,5,5,7,7,9,13,15,17 5th smallest = 7 ALGORITHM STEPS 1 Initialize Start with first row as initial sums: [1,3,11] 2 Use Min-Heap Merge sums with next row using priority queue 3 Keep Top K Only track k smallest sums at each step 4 Return Kth After all rows processed, return kth element Min-Heap State: Top 5 sums: [3, 5, 5, 7, 7] FINAL RESULT Sorted Array Sums: 3 1st 5 2nd 5 3rd 7 4th 7 5th Output: 7 OK - Verified! 5th smallest sum = 7 Combinations: 1+6 or 3+4 Both equal 7 Key Insight: Use a min-heap to efficiently merge sorted rows. Instead of generating all m^n combinations, keep only the k smallest sums at each step. This reduces complexity from O(m^n) to O(n * k * m * log(k*m)). The rows being sorted ensures we can prune larger sums early in the heap merge process. TutorialsPoint - Find the Kth Smallest Sum of a Matrix With Sorted Rows | Optimal Solution
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