Leetcode Problem 373. Find K Pairs with Smallest Sums
373. Find K Pairs with Smallest Sums
Leetcode Solutions
Using Min Heap to Find K Smallest Sum Pairs
Initialize a min heap to store tuples of the form (sum, index in nums1, index in nums2).
Add the first pair (nums1[0] + nums2[0], 0, 0) to the min heap.
Initialize a set to keep track of visited index pairs to prevent duplicates.
Initialize an empty list to store the k smallest sum pairs.
While the min heap is not empty and we have not found k pairs:
a. Pop the smallest sum pair from the min heap.
b. Add the corresponding values from nums1 and nums2 to the result list.
c. For the indices (i, j) of the popped pair, if i + 1 is within bounds and (i + 1, j) is not visited, add the new pair to the min heap.
d. Similarly, if j + 1 is within bounds and (i, j + 1) is not visited, add the new pair to the min heap.