For a pair ,
and
.
Sweep line
We can group the pairs by distinct ‘s. Since a group has a fixed
and
nums2 is sorted, we can consider each group as a sorted list of pairs . Keeping group heads in a min-heap, we can generate the pairs in sorted order of their sums with sweep line.

Say len(nums1) = .
Time: , space:
.
from heapq import heapify, heappush as push, heappop as pop
class Solution:
def kSmallestPairs(
self, nums1: List[int], nums2: List[int], k: int
) -> List[List[int]]:
min_heap = [(first + nums2[0], first, nums2[0], 1) for first in nums1]
heapify(min_heap)
pairs = []
while min_heap and len(pairs) < k:
_, first, second, next_second_index = pop(min_heap)
pairs.append([first, second])
if next_second_index == len(nums2):
continue
second = nums2[next_second_index]
push(min_heap, (first + second, first, second, next_second_index + 1))
return pairs
Leave a comment