Find the Kth Smallest Sum of a Matrix With Sorted Rows — LeetCode 1439 Python Solution

HardArrayBinary SearchMatrixHeap (Priority Queue)
Problem
#1439
Reading time
2 min

The 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.

Example

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:

Python solution

Python
class Solution:
    def kthSmallest(self, mat: List[List[int]], k: int) -> int:
        pre = [0]
        for cur in mat:
            pre = sorted(a + b for a in pre for b in cur[:k])[:k]
        return pre[-1]

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows?
LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows is rated Hard on LeetCode.
What topics does LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows cover?
LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows is tagged Array, Binary Search, Matrix and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview