AlgoMaster Logo

Find K Pairs with Smallest Sums

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

In the brute force approach, we aim to calculate the sum of every possible pair from two arrays and sort these sums to find the k smallest sums.

Steps:

  1. Iterate through every element in the first array nums1.
  2. For each element in nums1, iterate through every element in the second array nums2.
  3. Create all possible pairs and store them with their sums.
  4. Sort the list of pairs based on the sum.
  5. Return the first k pairs.

Code:

2. Heap Approach

Intuition:

We can improve our solution by using a max heap to maintain the k smallest pairs found so far while iterating through the array.

Steps:

  1. Use a Max-Heap to keep track of the smallest k sums.
  2. Iterate through all pairs of the given arrays.
  3. Maintain only k sums in the heap, and pop the largest if the heap size exceeds k.
  4. Return the k pairs in the heap.

Code:

3. Optimized Heap Approach using Min-Heap

Intuition:

Instead of using a max heap, we can use a min heap (priority queue) to efficiently get the next smallest sum.

Steps:

  1. Initiate a Min-Heap to store potential pairs, starting with the smallest possible pairs (first elements of nums1 with first element of nums2).
  2. Extract the smallest pair from the heap.
  3. Push the next possible pairs incrementally from nums1 and nums2.
  4. Repeat until we find k pairs.

Code: