You are given two integer arrays nums1
and nums2
sorted in ascending order and an integer k
.
Define a pair (u, v)
which consists of one element from nums1
and one element from nums2
.
Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk)
with the smallest sums.
k
is greater than the total number of possible pairs?
nums1
and nums2
?
nums1
and nums2
?
heapq
module.nums1
and nums2
into the Min-Heap with their sums as the priority.nums1
with every element from nums2
(or vice versa) and push these pairs into the Min-Heap.k
times or until the heap is exhausted.from heapq import heappush, heappop
def kSmallestPairs(nums1, nums2, k):
if not nums1 or not nums2 or k == 0:
return []
min_heap = []
res = []
# Initialize the heap
for i in range(min(len(nums1), k)):
heappush(min_heap, (nums1[i] + nums2[0], i, 0))
# Extract the smallest pairs
while min_heap and len(res) < k:
sum_val, i, j = heappop(min_heap)
res.append((nums1[i], nums2[j]))
if j + 1 < len(nums2):
heappush(min_heap, (nums1[i] + nums2[j + 1], i, j + 1))
return res
min(len(nums1), k)
elements into the heap.k
heap operations, each taking O(log(min(len(nums1), k))).The overall time complexity is O(k log(min(len(nums1), k))), making this approach efficient for the given problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?