Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Heap & Priority Queue

K Smallest Pair Sums

Medium · Heap & Priority Queue · Asked at Amazon, Google, LinkedIn, Uber

Arrays A (length n) and B (length m) are sorted in non-decreasing order. Among all n × m sums A[i] + B[j], print the k smallest, in non-decreasing order.

Input

First line: n m k. Second line: array A. Third line: array B.

Output

k sums in non-decreasing order, space-separated.

Constraints

The smallest sum is A[0] + B[0]. Put (A[i] + B[0], i, 0) for every i (up to k of them) in a min-heap. Each time you pop (i, j), push (i, j + 1) — the next candidate from that row. k pops give the answer in O(k log k).

Example 1

Input

3 3 3
1 7 11
2 4 6

Output

3 5 7

Example 2

Input

2 3 4
1 1
1 2 3

Output

2 2 3 3

Hints

  1. Think of the sums as an n × m grid where every row and every column is sorted.
  2. The smallest unused sum is always the next unused cell of some row.
  3. Keep, for each row, only its next candidate in a min-heap.

Approach

Seed the heap with (A[i] + B[0], i, 0) for the first min(n, k) rows — a row beyond k can never contribute to the k smallest. Pop k times; each pop (v, i, j) outputs v and pushes the next cell of the same row, (A[i] + B[j + 1], i, j + 1). The heap never holds more than k entries. Sums reach 2 × 10^9, so use 64-bit integers.

Complexity: O(k log k) time · O(k) space

Solution

C++ solution

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

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m, k;
    cin >> n >> m >> k;
    vector<long long> A(n), B(m);
    for (auto &x : A) cin >> x;
    for (auto &x : B) cin >> x;
    priority_queue<tuple<long long, int, int>, vector<tuple<long long, int, int>>, greater<>> pq;
    for (int i = 0; i < min(n, k); i++) pq.push({A[i] + B[0], i, 0});
    for (int c = 0; c < k; c++) {
        auto _b = pq.top();
        auto v = get<0>(_b);
        auto i = get<1>(_b);
        auto j = get<2>(_b);
        pq.pop();
        cout << v << (c + 1 < k ? ' ' : '\n');
        if (j + 1 < m) pq.push({A[i] + B[j + 1], i, j + 1});
    }
    return 0;
}

Python solution

import heapq
import sys

data = list(map(int, sys.stdin.read().split()))
n, m, k = data[0], data[1], data[2]
A = data[3 : 3 + n]
B = data[3 + n : 3 + n + m]
heap = [(A[i] + B[0], i, 0) for i in range(min(n, k))]
heapq.heapify(heap)
out = []
for _ in range(k):
    v, i, j = heapq.heappop(heap)
    out.append(v)
    if j + 1 < m:
        heapq.heappush(heap, (A[i] + B[j + 1], i, j + 1))
print(*out)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        int m = (int) in.nval;
        in.nextToken();
        int k = (int) in.nval;
        long[] A = new long[n], B = new long[m];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            A[i] = (long) in.nval;
        }
        for (int i = 0; i < m; i++) {
            in.nextToken();
            B[i] = (long) in.nval;
        }
        PriorityQueue<long[]> pq = new PriorityQueue<>((x, y) -> Long.compare(x[0], y[0]));
        for (int i = 0; i < Math.min(n, k); i++) pq.add(new long[] {A[i] + B[0], i, 0});
        StringBuilder sb = new StringBuilder();
        for (int c = 0; c < k; c++) {
            long[] t = pq.poll();
            sb.append(t[0]).append(c + 1 < k ? " " : "\n");
            int i = (int) t[1], j = (int) t[2];
            if (j + 1 < m) pq.add(new long[] {A[i] + B[j + 1], i, j + 1});
        }
        System.out.print(sb);
    }
}

Solve K Smallest Pair Sums online · All practice problems