Find K Pairs with Smallest Sums

 You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.


Define a pair (u, v) which consists of one element from the first array and one element from the second array.


Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.


 


Example 1:


Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3

Output: [[1,2],[1,4],[1,6]]

Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Example 2:


Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2

Output: [[1,1],[1,1]]

Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

 Brurte Force :

import java.util.*;

class Solution {
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
            (a, b) -> b[0] - a[0]  // Max heap based on sum
        );

        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                int sum = nums1[i] + nums2[j];

                if (maxHeap.size() < k) {
                    maxHeap.offer(new int[]{sum, nums1[i], nums2[j]});
                } else {
                    if (sum < maxHeap.peek()[0]) {
                        maxHeap.poll();
                        maxHeap.offer(new int[]{sum, nums1[i], nums2[j]});
                    } else {
                        break; // Since arrays are sorted, further j will give higher sum
                    }
                }
            }
        }

        // Extract from maxHeap
        List<List<Integer>> result = new ArrayList<>();
        while (!maxHeap.isEmpty()) {
            int[] top = maxHeap.poll();
            result.add(Arrays.asList(top[1], top[2]));
        }

        // Optional: reverse because it's a max heap
        Collections.reverse(result);
        return result;
    }
}



Optimal Approach :


🔑 Key Idea:

  • Use a Min Heap to store elements based on their sum nums1[i] + nums2[j]

  • Only push pairs where nums1[i] is fixed and nums2[j] moves forward (j++)

  • Always expand the next element in nums2 from the current (i, j).

class Solution {
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
 List<List<Integer>> result = new ArrayList<>();

        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);

        for (int i = 0; i < Math.min(k, nums1.length); i++) {
            heap.offer(new int[]{nums1[i] + nums2[0], i, 0});
        }

        while (k-- > 0 && !heap.isEmpty()) {
            int[] top = heap.poll();
            int i = top[1];
            int j = top[2];

            result.add(Arrays.asList(nums1[i], nums2[j]));

            // ✅ Fix here
            if (j + 1 < nums2.length) {
                heap.offer(new int[]{nums1[i] + nums2[j + 1], i, j + 1});
            }
        }

        return result;


    }
}



Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence