Space
Open
From Fieldwork
Scales
Archive
When we introduce the notion of forming pairs, we're effectively working over the Cartesian product, which we can think of in terms of a matrix.
So we have to consider the diagonal. So we throw it all into a heap rather than comparing the immediate pointer-by-pointer thing.
We encounter this inflection point where pointers are no longer good enough when the situation involves an additional degree of freedom. We're exploring a frontier, not a path.
It's still greedy, but it's a globally greedy strategy rather than a locally greedy one.
Two-pointers work when the set of possible next answers can be represented by a constant-size boundary (usually 2 items).
So we need a data structure that answers:
"Among all frontier candidates, which sum is smallest right now?"
Once our problem's natural candidate is no longer constant-size, that's the inflection point where we typically need something like:
class Solution:
import heapq
def kSmallestPairs(self, nums1, nums2, k):
if not nums1 or not nums2 or k <= 0:
return []
min_heap = []
res = []
# 1. Initialize the heap with the first element of nums1
# paired with the first few elements of nums2.
# We only need to go up to min(len(nums1), k)
for i in range(min(len(nums1), k)):
heapq.heappush(min_heap, (nums1[i] + nums2[0], i, 0))
# 2. Extract the smallest sum and push the next potential candidate
while min_heap and len(res) < k:
current_sum, i, j = heapq.heappop(min_heap)
res.append([nums1[i], nums2[j]])
# If there is a next element in nums2, pair it with the current nums1[i]
if j + 1 < len(nums2):
heapq.heappush(min_heap, (nums1[i] + nums2[j+1], i, j+1))
return resPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode