Find the Kth Smallest Sum of a Matrix With Sorted Rows Problem
Description
LeetCode Problem 1439.
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 k^th smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5
Output: 7
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
Example 2:
Input: mat = [[1,3,11],[2,4,6]], k = 9
Output: 17
Example 3:
Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
Output: 9
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.
Constraints:
m == mat.lengthn == mat.length[i]1 <= m, n <= 401 <= mat[i][j] <= 50001 <= k <= min(200, n^m)mat[i]is a non-decreasing array.
Solution
Approach: Keep the k Smallest Sums Row by Row
There can be up to 4040 arrays, but we only need the k-th smallest sum with k <= 200. Go row by row and keep only the k smallest sums of the rows seen so far.
That is safe: if a partial sum is not among the k smallest after some row, then at least k partial sums are smaller or equal. Adding the same choices for the remaining rows to each of them gives k full sums that are not larger, so this partial sum can never lead to one of the k smallest full sums.
So start with best = [0]. For each row, add every value of the row to every sum in best, sort, and keep the first k. Since the row is sorted, only its first k values can matter. After the last row, best[k - 1] is the answer.
Complexity: O(m · k · n · log(k · n)) time, about 40 · 8000 · 13 steps at most, and O(k · n) extra space for one round of sums.
class Solution:
def kthSmallest(self, mat: List[List[int]], k: int) -> int:
best = [0] # the k smallest sums using the rows seen so far
for row in mat:
# a sum outside the k smallest so far can never get back into the k smallest
best = sorted(a + b for a in best for b in row[:k])[:k]
return best[k - 1]