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 thekth
smallest array sum among all possible arrays.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
m == mat.length
n == mat.length[i]
1 <= m, n <= 40
1 <= mat[i][j] <= 5000
1 <= k <= min(200, nm)
mat[i]
is a non-decreasing array.
Solution
Method 1 – Min Heap + Row-wise Merging
Intuition
We want to find the k-th smallest sum by picking one element from each row. Since each row is sorted, we can use a min-heap to always expand the smallest possible sum, similar to merging k sorted lists.
Approach
- Start with the first row as the initial list of sums.
- For each subsequent row, merge the current list of smallest sums with the new row using a min-heap, always keeping only the k smallest sums.
- Repeat until all rows are processed.
- The k-th smallest sum will be the last in the heap after processing all rows.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n^2 * k * log k)
, because for each of m rows, we merge up to k sums with n elements, and keep the k smallest using a heap. - 🧺 Space complexity:
O(k)
, as we only keep up to k sums at each step.