bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

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

  1. Initialize a min heap to store tuples of the form (sum, index in nums1, index in nums2).
  2. Add the first pair (nums1[0] + nums2[0], 0, 0) to the min heap.
  3. Initialize a set to keep track of visited index pairs to prevent duplicates.
  4. Initialize an empty list to store the k smallest sum pairs.
  5. 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.
  6. Return the list of k smallest sum pairs.
UML Thumbnail

Brute Force Approach with Sorting

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...