Find the Kth Smallest Sum of a Matrix With Sorted Rows - Problem

Imagine you're a data analyst tasked with finding specific statistical insights from a structured dataset. You have an m ร— n matrix where each row is sorted in non-decreasing order, representing different categories of data points.

Your challenge: select exactly one element from each row to form a combination, then find the k-th smallest sum among all possible combinations.

For example, with matrix [[1,3,11],[2,4,6]] and k=5:

  • Possible combinations: [1,2], [1,4], [1,6], [3,2], [3,4], [3,6], [11,2], [11,4], [11,6]
  • Corresponding sums: [3, 5, 7, 5, 7, 9, 13, 15, 17]
  • Sorted sums: [3, 5, 5, 7, 7, 9, 13, 15, 17]
  • The 5th smallest sum is 7

Can you efficiently find this without generating all possible combinations?

Input & Output

example_1.py โ€” Basic case
$ Input: mat = [[1,3,11],[2,4,6]], k = 5
โ€บ Output: 7
๐Ÿ’ก Note: All possible combinations: [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 sums: [3,5,5,7,7,9,13,15,17]. The 5th smallest is 7.
example_2.py โ€” Single row
$ Input: mat = [[1,10,10,10]], k = 3
โ€บ Output: 10
๐Ÿ’ก Note: Only one row, so combinations are just the elements: [1], [10], [10], [10]. Sorted: [1,10,10,10]. The 3rd smallest is 10.
example_3.py โ€” Small k value
$ Input: mat = [[1,1,10],[2,2,9]], k = 1
โ€บ Output: 3
๐Ÿ’ก Note: The smallest possible sum is always mat[0][0] + mat[1][0] + ... = 1 + 2 = 3. So the 1st smallest sum is 3.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 โ‰ค m, n โ‰ค 40
  • 1 โ‰ค mat[i][j] โ‰ค 5000
  • 1 โ‰ค k โ‰ค min(200, nm)
  • mat[i] is sorted in non-decreasing order
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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