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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code