Skip to content
BytePatterns

K Smallest Pair Sums

MediumTwo Heaps & K-Way Merge#k-way-merge#min-heap~30m

Problem

Two lists a and b are sorted in ascending order. A pair takes one value from a and one from b. Return the k pairs with the smallest sums, smallest sum first, breaking ties by the position in a and then by the position in b. If there are fewer than k pairs in total, return all of them.

Examples

Input:  a = [1, 7, 11], b = [2, 4, 6], k = 3
Output: [[1, 2], [1, 4], [1, 6]]
Why:    the next smallest sum, 7 + 2, is larger than all three
Input:  a = [1, 1, 2], b = [1, 2, 3], k = 2
Output: [[1, 1], [1, 1]]
Why:    equal values at different positions are different pairs
Input:  a = [1, 2], b = [3], k = 3
Output: [[1, 3], [2, 3]]
Why:    edge case, only two pairs exist, so both are returned

Hints

0 / 3

Stuck on the idea rather than the code? K-Way Merge covers it.