KatInterview

373. Find K Pairs with Smallest Sums

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the k pairs with the smallest sums, where each pair (u, v) consists of one element u from a sorted array nums1 and one element v from another sorted array nums2.

Solution

Find K Pairs with Smallest Sums in Python

import heapq

class Solution:
    def kSmallestPairs(self, nums1: list[int], nums2: list[int], k: int) -> list[list[int]]:
        m, n = len(nums1), len(nums2)
        
        if not nums1 or not nums2 or k == 0:
            return []
        
        # Min-heap to store tuples of (sum, index_in_nums1, index_in_nums2)
        min_heap = []
        result = []
        
        # This is a k-way merge problem. We have `m` conceptual sorted lists,
        # where the i-th list is (nums1[i]+nums2[0], nums1[i]+nums2[1], ...).
        # We initialize the heap with the first element of each of these lists.
        # We only need to consider up to the first `k` elements of nums1.
        for i in range(min(m, k)):
            # Push (sum, index1, index2) to the heap
            heapq.heappush(min_heap, (nums1[i] + nums2[0], i, 0))
            
        # Extract the smallest pair `k` times, or until the heap is empty.
        while k > 0 and min_heap:
            # Pop the pair with the smallest sum
            current_sum, i, j = heapq.heappop(min_heap)
            
            # Add the pair to the result
            result.append([nums1[i], nums2[j]])
            k -= 1
            
            # If there's a next element in nums2 for the current element from nums1,
            # push the next pair from the i-th conceptual list into the heap.
            if j + 1 < n:
                heapq.heappush(min_heap, (nums1[i] + nums2[j+1], i, j+1))
        
        return result

Find K Pairs with Smallest Sums in Java

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

        if (m == 0 || n == 0 || k == 0) {
            return result;
        }

        // Min-heap to store pairs of indices [i, j] from nums1 and nums2.
        // The comparator sorts pairs based on their sum.
        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> 
            (nums1[a[0]] + nums2[a[1]]) - (nums1[b[0]] + nums2[b[1]])
        );

        // Initially, push the first element of nums2 paired with the first k elements
        // (or all, if m < k) of nums1 into the heap.
        // This seeds the heap with the smallest pair from each of the m "conceptual" sorted lists.
        for (int i = 0; i < m && i < k; i++) {
            minHeap.offer(new int[]{i, 0});
        }

        while (k > 0 && !minHeap.isEmpty()) {
            // Extract the pair with the smallest sum from the heap.
            int[] current = minHeap.poll();
            int i = current[0];
            int j = current[1];

            // Add the actual numbers to the result list.
            result.add(List.of(nums1[i], nums2[j]));
            k--;

            // If the current element from nums1 has a next element in nums2,
            // add the next pair to the heap. This advances the pointer in the j-th list.
            if (j + 1 < n) {
                minHeap.offer(new int[]{i, j + 1});
            }
        }

        return result;
    }
}

Find K Pairs with Smallest Sums in C++

class Solution {
public:
    vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
        vector<vector<int>> result;
        int m = nums1.size();
        int n = nums2.size();

        if (m == 0 || n == 0 || k == 0) {
            return result;
        }

        // The priority queue will store tuples of {sum, index_in_nums1, index_in_nums2}.
        // We use a min-heap, so we use std::greater.
        // A tuple could be {sum, i, j}. Storing as vector<int> also works because
        // vector comparison is lexicographical, which fits our need.
        auto compare = [&](const pair<int, int>& a, const pair<int, int>& b) {
            return nums1[a.first] + nums2[a.second] > nums1[b.first] + nums2[b.second];
        };
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(compare)> min_heap(compare);

        // Push the initial pairs into the min-heap. We only need to consider
        // the first k elements of nums1, as any pair starting with nums1[k] or later
        // will have a sum larger than or equal to k pairs we can form with nums1[0]...nums1[k-1].
        for (int i = 0; i < m && i < k; ++i) {
            min_heap.push({i, 0});
        }

        while (k > 0 && !min_heap.empty()) {
            // Get the pair with the smallest sum
            pair<int, int> top = min_heap.top();
            min_heap.pop();
            int i = top.first;
            int j = top.second;

            // Add the pair to the result list
            result.push_back({nums1[i], nums2[j]});
            k--;

            // If there's a next element in nums2 for the current element of nums1,
            // push the new pair into the heap.
            if (j + 1 < n) {
                min_heap.push({i, j + 1});
            }
        }

        return result;
    }
};

Find K Pairs with Smallest Sums in TypeScript

/**
 * A simple MinPriorityQueue implementation for LeetCode environment.
 */
class MinPriorityQueue {
    private heap: [number, number, number][] = [];

    // Min-heap based on the sum (the first element of the tuple)
    private compare(a: [number, number, number], b: [number, number, number]): boolean {
        return a[0] < b[0];
    }

    private siftUp(index: number): void {
        let parentIndex = Math.floor((index - 1) / 2);
        while (index > 0 && this.compare(this.heap[index], this.heap[parentIndex])) {
            [this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
            index = parentIndex;
            parentIndex = Math.floor((index - 1) / 2);
        }
    }

    private siftDown(index: number): void {
        const n = this.heap.length;
        while (true) {
            let leftChildIndex = 2 * index + 1;
            let rightChildIndex = 2 * index + 2;
            let smallestIndex = index;

            if (leftChildIndex < n && this.compare(this.heap[leftChildIndex], this.heap[smallestIndex])) {
                smallestIndex = leftChildIndex;
            }
            if (rightChildIndex < n && this.compare(this.heap[rightChildIndex], this.heap[smallestIndex])) {
                smallestIndex = rightChildIndex;
            }
            if (smallestIndex === index) {
                break;
            }
            [this.heap[index], this.heap[smallestIndex]] = [this.heap[smallestIndex], this.heap[index]];
            index = smallestIndex;
        }
    }

    push(val: [number, number, number]): void {
        this.heap.push(val);
        this.siftUp(this.heap.length - 1);
    }

    pop(): [number, number, number] | undefined {
        if (this.isEmpty()) return undefined;
        [this.heap[0], this.heap[this.heap.length - 1]] = [this.heap[this.heap.length - 1], this.heap[0]];
        const val = this.heap.pop();
        if (!this.isEmpty()) {
            this.siftDown(0);
        }
        return val;
    }

    isEmpty(): boolean {
        return this.heap.length === 0;
    }
}

function kSmallestPairs(nums1: number[], nums2: number[], k: number): number[][] {
    const m = nums1.length;
    const n = nums2.length;
    const result: number[][] = [];

    if (m === 0 || n === 0 || k === 0) {
        return result;
    }

    // Min-heap to store tuples of [sum, index_in_nums1, index_in_nums2]
    const minHeap = new MinPriorityQueue();

    // Seed the heap with the first element of nums2 paired with the first k elements of nums1.
    for (let i = 0; i < Math.min(m, k); i++) {
        minHeap.push([nums1[i] + nums2[0], i, 0]);
    }

    while (k > 0 && !minHeap.isEmpty()) {
        // Pop the pair with the smallest sum.
        const [currentSum, i, j] = minHeap.pop()!;

        // Add the pair to the result list.
        result.push([nums1[i], nums2[j]]);
        k--;

        // If there's a next element in nums2 for the current nums1 element,
        // push the new pair into the heap.
        if (j + 1 < n) {
            minHeap.push([nums1[i] + nums2[j + 1], i, j + 1]);
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.