#1439

Find the Kth Smallest Sum of a Matrix With Sorted Rows

Hard
ArrayBinary SearchHeap (Priority Queue)MatrixHeap (Priority Queue)Array
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(k log m)
Space
O(1)
O(m)
💡

Intuition

Time O(k log m)Space O(m)

Using a min-heap allows us to efficiently track the smallest sums without generating all combinations. We can incrementally build the sums and explore new candidates based on the current smallest sum.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a min-heap and add the smallest sum (the first element of each row) along with their indices.
  2. 2Step 2: Pop the smallest sum from the heap and push new sums formed by incrementing the indices of the rows.
  3. 3Step 3: Repeat until we pop the k-th smallest sum.
solution.py17 lines
1# Full working Python code
2import heapq
3
4def kthSmallest(mat, k):
5    m, n = len(mat), len(mat[0])
6    min_heap = []
7    initial_sum = sum(row[0] for row in mat)
8    heapq.heappush(min_heap, (initial_sum, [0] * m))
9    for _ in range(k):
10        current_sum, indices = heapq.heappop(min_heap)
11        for i in range(m):
12            if indices[i] + 1 < n:
13                new_indices = indices[:]
14                new_indices[i] += 1
15                new_sum = current_sum - mat[i][indices[i]] + mat[i][new_indices[i]]
16                heapq.heappush(min_heap, (new_sum, new_indices))
17    return current_sum

Complexity note: This complexity arises because we perform k operations on a heap that can grow to size m, where m is the number of rows.

  • 1Using a min-heap allows us to efficiently track the smallest sums without generating all combinations.
  • 2The matrix's sorted rows mean that we can always find the next smallest sum by incrementing indices.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.