127. Pairs with the Smallest Sums
Medium
A purchasing hub maintains two sorted price lists, lista_a and lista_b. Each possible pair combines one price from each list.
Return the k pairs with the smallest sums, or all possible pairs if there are fewer than k. Represent each pair as [a, b], where a comes from lista_a and b comes from lista_b. Sort the result by increasing sum; break ties by increasing a, then by increasing b. If values are repeated in the lists, each combination of positions counts as a pair, even when some resulting pairs are identical.
Example 1
Input: lista_a = [1, 7, 11], lista_b = [2, 4, 6], k = 3
Output: [[1, 2], [1, 4], [1, 6]]
Explanation: The three smallest-sum pairs combine the first value in `lista_a` with values from `lista_b`.
Example 2
Input: lista_a = [1, 1, 2], lista_b = [1, 2, 3], k = 5
Output: [[1, 1], [1, 1], [1, 2], [1, 2], [2, 1]]
Explanation: Combinations from different positions are kept, and ties are ordered by value.
Example 3
Input: lista_a = [], lista_b = [2, 3], k = 4
Output: []
Constraints
- 0 <= lista_a.length, lista_b.length <= 10^5
- Both lists are sorted in nondecreasing order.
- -10^9 <= lista_a[i], lista_b[j] <= 10^9
- 0 <= k <= 10^5
Heap
Saved in this browser
Caso 1
lista_a =
[1,7,11]
lista_b =
[2,4,6]
k =
3
Expected =
[[1,2],[1,4],[1,6]]
Caso 2
lista_a =
[1,1,2]
lista_b =
[1,2,3]
k =
5
Expected =
[[1,1],[1,1],[1,2],[1,2],[2,1]]
Caso 3
lista_a =
[]
lista_b =
[2,3]
k =
4
Expected =
[]
Run checks these 3 cases. Submit runs all 12, including hidden ones.