Leetcode 373. Find K Pairs with Smallest Sums
Given two integer arrays nums1 and nums2 sorted in ascending order and an integer k, return the k pairs (u,v) with the smallest sums where u is from nums1 and v is from nums2.
nums1 = [1,7,11], nums2 = [2,4,6], k = 3[[1,2],[1,4],[1,6]]nums1 = [1,1,2], nums2 = [1,2,3], k = 2[[1,1],[1,1]]nums1 = [1,2], nums2 = [3], k = 3[[1,3],[2,3]]1 <= nums1.length, nums2.length <= 10^4-10^9 <= nums1[i], nums2[i] <= 10^9nums1 and nums2 are both sorted in ascending order.1 <= k <= 10^4nums1 and nums2 arrays are already sorted in ascending order.k is larger than the number of possible pairs, should we return all possible pairs?
k is larger than the total number of pairs, return all possible pairs.nums1 and the first element of nums2.nums2 for the current element in nums1.(sum, index1, index2), where sum = nums1[index1] + nums2[index2].(nums1[index1], nums2[index2]) to the result, and push the next pair involving index1.O(min(k, n)) where n is the number of elements in nums1.O(log k).O(k log k) time if k is much smaller than the product of lengths of nums1 and nums2.import java.util.*;
class Solution {
public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<int[]> result = new ArrayList<>();
if (nums1.length == 0 || nums2.length == 0 || k == 0) return result;
PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for (int i = 0; i < nums1.length && i < k; i++) {
minHeap.add(new int[] {nums1[i] + nums2[0], i, 0});
}
while (k > 0 && !minHeap.isEmpty()) {
int[] current = minHeap.poll();
int sum = current[0];
int i = current[1];
int j = current[2];
result.add(new int[] {nums1[i], nums2[j]});
k--;
if (j + 1 < nums2.length) {
minHeap.add(new int[] {nums1[i] + nums2[j + 1], i, j + 1});
}
}
return result;
}
}
This code uses a min heap to ensure the smallest pairs are processed first, efficiently keeping track of the next smallest pair to consider from nums1 and nums2.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?