mediumHeapHeap / Priority Queue

Find K Pairs with Smallest Sums

mediumTime: O(k log k)Space: O(k)

Signals to notice

k smallest pairs from two sorted arraysdon't enumerate all pairslazy expansion

Brute force first

Generate all n×m pairs, sort by sum, take first k. Creates every possible pair even though you only need k. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Min-heap starting with (nums1[0]+nums2[0], 0, 0). Pop the smallest, then push the next pair in each dimension. Like BFS on a 2D grid of sums — you only explore what's needed. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

The heap always contains the frontier of unexplored pairs. The smallest unexplored sum is always on top. You never need to look beyond k expansions because each expansion considers the next cheapest neighbor. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Pushing duplicate pairs — use a visited set or only expand in one direction per pop to avoid processing the same (i,j) pair twice. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Heap / Priority Queue Pattern