Python coding

The k smallest pair sums

You get two lists of integers, a and b, each sorted in non-decreasing order, and an integer k. A pair takes one position from a and one from b, so there are len(a) * len(b) pairs; equal values at different positions are different pairs. Return the k smallest pair sums a[i] + b[j], in non-decreasing order. k is between 0 and the number of pairs, and values may be negative or repeat.

Aim for about O(k log k): don't build every pair when k is small.

Besides the tests, one large input (1,200 values each, k = 2,000) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • smallest_pair_sums([1,7,11], [2,4,6], 3) → [3,5,7]
  • smallest_pair_sums([1,1,2], [1,2,3], 4) → [2,2,3,3]
  • smallest_pair_sums([-3,0,5], [2,2], 6) → [-1,-1,2,2,7,7]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Picture a grid whose cell (i, j) holds a[i] + b[j]: every row and every column is sorted. The smallest sum is at (0, 0), and each next one sits beside a cell already taken.

Hint 2

Seed a min-heap with (a[i] + b[0], i, 0) for the first k rows. Each pop is the next answer; then push the cell to its right, (i, j + 1), if it exists.

Hint 3

Two pointers are not enough: the next smallest sum can come from any row already started, so every row's frontier cell must wait in the heap.

Solution and why it works
pythonO(k log m), m = min(k, len(a)) · O(m) besides the output
import heapq


def smallest_pair_sums(a: list[int], b: list[int], k: int) -> list[int]:
    heap = [(a[i] + b[0], i, 0) for i in range(min(k, len(a)))]   # row i starts at b[0]
    heapq.heapify(heap)
    sums = []
    while len(sums) < k:
        total, i, j = heapq.heappop(heap)
        sums.append(total)
        if j + 1 < len(b):
            heapq.heappush(heap, (a[i] + b[j + 1], i, j + 1))   # the next cell in row i
    return sums

Picture the sums as a grid with sorted rows and columns. The heap holds one frontier cell per started row, that row's smallest untaken sum, so its root is the next answer overall. Each of the k pops pushes at most one cell, O(log k) each. Row i ≥ k is never needed: the k rows above it already start with sums at least as small. The trap is building and sorting all len(a) × len(b) sums to keep only k of them.