KatInterview

Lowest-Sum Pairs Across Two Sorted Lists

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapk-way mergesorted arrays

Last updated

Select the k cheapest cross-array pairs from two sorted lists using a heap-based k-way merge, with a deterministic ordering for ties.

You are given two integer lists, first and second, each sorted in non-decreasing order, and a positive integer k.

A pair is a two-element list [a, b] where a is taken from first and b is taken from second. Two pairs are considered different if they use different positions, even when their values are equal. Pairs that use different positions but have equal values therefore each count separately.

Return the k pairs with the smallest sums a + b, as a list of [a, b] lists, in the following order:

  1. Ascending by sum a + b.
  2. If sums are equal, ascending by a.
  3. If both the sum and a are equal, ascending by b. This also means b is determined by the earlier rules, so such pairs are identical in value.

If fewer than k pairs exist in total (that is, len(first) * len(second) < k), return every possible pair in the order above.

Constraints

  • 1 <= len(first), len(second) <= 10^5
  • -10^9 <= first[i], second[j] <= 10^9
  • 1 <= k <= 10^4
  • Both lists are sorted in non-decreasing order.
  • The total number of pairs can reach 10^10, so generating every pair is not feasible.

Examples

Example 1

Input: smallest_sum_pairs([1, 7, 11], [2, 4, 6], 3)

Output: [[1, 2], [1, 4], [1, 6]]

Example 2

Input: smallest_sum_pairs([1, 1, 2], [1, 2, 3], 2)

Output: [[1, 1], [1, 1]]

Example 3

Input: smallest_sum_pairs([1, 2], [3, 4], 10)

Output: [[1, 3], [1, 4], [2, 3], [2, 4]]

Example 4

Input: smallest_sum_pairs([-1, 0, 2], [-3, 1, 4], 4)

Output: [[-1, -3], [0, -3], [2, -3], [-1, 1]]

Hints

Hint 1

Think of all pairs as a grid: for a fixed element of the first list, its sums with the second list never decrease as you move along the second list. Each row is already sorted.

Hint 2

You are effectively merging several sorted rows and keeping only the first k results. A min-heap holding one candidate per row is the standard tool.

Hint 3

Only the first min(k, len(first)) rows can ever matter. Seed the heap with each such row's first pair, and after popping a pair, push the next pair in the same row. Use a heap key of (sum, a, b, row, col) so ties come out in the required order.