LeetCode 373: Find K Pairs with Smallest Sums Solution

Master LeetCode problem 373 (Find K Pairs with Smallest Sums), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

373. Find K Pairs with Smallest Sums

Problem Explanation

Explanation

To find the k pairs with the smallest sums, we can use a min heap to keep track of the pairs with the smallest sums. We start by pushing pairs of indices (0, 0) to the min heap and iterate until we have found k pairs or the min heap is empty. During each iteration, we pop the pair with the smallest sum from the heap, add it to the result, and potentially push the next pair from the same row or column to the heap.

Time complexity: O(k log k)
Space complexity: O(k)

Solution Code

class Solution {
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<List<Integer>> result = new ArrayList<>();
        if(nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0 || k == 0) {
            return result;
        }
        
        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> (nums1[a[0]] + nums2[a[1]] - nums1[b[0]] - nums2[b[1]]));
        
        for(int i = 0; i < Math.min(nums1.length, k); i++) {
            minHeap.offer(new int[]{i, 0});
        }
        
        while(k-- > 0 && !minHeap.isEmpty()) {
            int[] pair = minHeap.poll();
            result.add(Arrays.asList(nums1[pair[0]], nums2[pair[1]]));
            if(pair[1] < nums2.length - 1) {
                minHeap.offer(new int[]{pair[0], pair[1] + 1});
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 373 (Find K Pairs with Smallest Sums)?

This page provides optimized solutions for LeetCode problem 373 (Find K Pairs with Smallest Sums) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 373 (Find K Pairs with Smallest Sums)?

The time complexity for LeetCode 373 (Find K Pairs with Smallest Sums) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 373 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 373 in Java, C++, or Python.

Back to LeetCode Solutions