Ctrl K

Lightest Pair Sums

Medium
You are given two lists left and right, both sorted in non-decreasing order, and a number k. A pair is one element of left and one element of right; elements at different positions make different pairs even when their values match. Order all pairs by their sum, and pairs with equal sums by the number from left, smaller first. Return the first k pairs in that order, each as [number from left, number from right]. There can be up to 10¹⁰ pairs, so listing them all is not an option.
Example 1
left=[1, 4, 9], right=[2, 3], k=4 → [[1, 2], [1, 3], [4, 2], [4, 3]]

The pair sums are 1+2=3, 1+3=4, 4+2=6, 4+3=7, 9+2=11, 9+3=12. Take the four lightest.

Example 2
left=[1, 2], right=[2, 3], k=3 → [[1, 2], [1, 3], [2, 2]]

[1, 3] and [2, 2] share the sum 4, so the pair with the smaller number from left comes first.

Example 3
left=[-2, -2], right=[5], k=2 → [[-2, 5], [-2, 5]]

Equal numbers at different positions make different pairs.

Constraints
  • 1 ≤ len(left), len(right) ≤ 10⁵
  • -10⁹ ≤ left[i], right[i] ≤ 10⁹
  • Both lists are sorted in non-decreasing order
  • 1 ≤ k ≤ 10⁴, k ≤ len(left) · len(right)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsK-th Highest Score MediumStudios for Recording Sessions MediumMost Common Values MediumK-th Smallest in a Sorted Grid MediumShortest Path of a Rolling Ball Medium
loading Python…
Input
left=[1, 4, 9], right=[2, 3], k=4
Expected
[[1, 2], [1, 3], [4, 2], [4, 3]]

Run checks the first 3 tests in your browser. Submit checks all 84 tests on the server, hidden ones included.