LeetCode 1439: Find the Kth Smallest Sum of a Matrix With Sorted Rows
Problem Description
Explanation
To find the kth smallest sum of arrays formed by choosing one element from each row of the given matrix with sorted rows, we can use a priority queue (min-heap) to keep track of the sums while exploring all possible combinations. We start by adding the first element of each row to the priority queue. Then in each iteration, we pop the smallest sum from the priority queue, add the next element from the corresponding row, and push the updated sum back into the priority queue. We repeat this process k times to find the kth smallest sum.
Algorithm:
- Initialize a priority queue with the first element from each row.
- Repeat the following steps k times:
- Pop the smallest sum from the priority queue.
- For each popped sum, add the next element from the corresponding row and push the updated sum back into the priority queue.
- Return the kth smallest sum.
Time Complexity: O(klogk) - We perform k iterations, each requiring logk time to adjust the priority queue.
Space Complexity: O(k) - We maintain a priority queue with at most k elements.
Solutions
import java.util.PriorityQueue;
class Solution {
public int kthSmallest(int[][] mat, int k) {
int m = mat.length, n = mat[0].length;
PriorityQueue<Integer> pq = new PriorityQueue<>();
int sum = 0;
for (int i = 0; i < m; i++) {
sum += mat[i][0];
}
pq.offer(sum);
for (int i = 0; i < k - 1; i++) {
int currentSum = pq.poll();
for (int j = 0; j < m; j++) {
for (int p = 1; p < n; p++) {
int newSum = currentSum - mat[j][p - 1] + mat[j][p];
pq.offer(newSum);
}
}
}
return pq.poll();
}
}
Loading editor...