The Min-Heap property
In a min-heap, the smallest value is always at the top. When you remove it, the heap quietly reorganises itself in about log n steps so the next smallest value rises to the top.
It is like a tournament ladder: when the champion leaves, a few matches decide the new one, without replaying the whole tournament.
import heapq
heapq.heapify(nums)
res = []
for _ in range(k):
res.append(heapq.heappop(nums))
return resThe array drawn as a tree: index 0 on top, then 1 and 2, then 3, 4, 5. No pointers, just positions. It isn't a heap yet.
Heaps across languages
Every language ships a ready-made heap, so you rarely write one yourself. In Python, the heapq module turns a list into a min-heap and pops from it. In C++, the priority queue with a "greater" comparison is a min-heap. In Java, a PriorityQueue is a min-heap by default.
Learn the one in your language and you'll reuse it on many problems.