Algo-Sim › Heaps & Priority Queues

Find K Pairs with Smallest Sums

Medium · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input

Given two sorted arrays, return the k pairs (one value from each) with the smallest sums.

Problem

Given two arrays nums1 and nums2, each sorted in ascending order, and an integer k, return the k pairs (u, v) with u from nums1 and v from nums2 that have the smallest sums.

Constraints

Edge cases to test

Follow-up questions

Why only push (i, j + 1) after popping (i, j)?
Seeding with (i, 0) for the first k rows and moving right covers every pair once, keeping the heap at most k: O(k log k).
What about the k-th smallest sum alone?
Binary search on the sum and count pairs ≤ mid with two pointers: O((m + n) log range).

Solution

Java

public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
    List<List<Integer>> result = new ArrayList<>();
    PriorityQueue<int[]> heap = new PriorityQueue<>(
            Comparator.comparingInt((int[] a) -> a[0]).thenComparingInt(a -> a[1]));
    for (int i = 0; i < Math.min(nums1.length, k); i++) {
        heap.offer(new int[] { nums1[i] + nums2[0], i, 0 });
    }
    while (k-- > 0 && !heap.isEmpty()) {
        int[] cur = heap.poll();
        int i = cur[1], j = cur[2];
        result.add(List.of(nums1[i], nums2[j]));
        if (j + 1 < nums2.length) {
            heap.offer(new int[] { nums1[i] + nums2[j + 1], i, j + 1 });
        }
    }
    return result;
}

Python

import heapq


def k_smallest_pairs(nums1, nums2, k):
    result = []
    heap = []  # entries are (sum, i, j)
    for i in range(min(len(nums1), k)):
        heapq.heappush(heap, (nums1[i] + nums2[0], i, 0))
    while heap and len(result) < k:
        _, i, j = heapq.heappop(heap)
        result.append([nums1[i], nums2[j]])
        if j + 1 < len(nums2):
            heapq.heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> kSmallestPairs(vector<int> &nums1, vector<int> &nums2, int k) {
        vector<vector<int>> result = {};
        priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> heap;
        for (int i = 0; i < std::min(int(nums1.size()), k); i++) {
            heap.push(vector<int>{nums1[i] + nums2[0], i, 0});
        }
        while (k-- > 0 && !heap.empty()) {
            vector<int> cur = heap.top();
            heap.pop();
            int i = cur[1], j = cur[2];
            result.push_back({nums1[i], nums2[j]});
            if (j + 1 < int(nums2.size())) {
                heap.push(vector<int>{nums1[i] + nums2[j + 1], i, j + 1});
            }
        }
        return result;
    }
};

More Heaps & Priority Queues problems