Data Structures · Visualization
Min-Heap: Extract Min
Min Heap
Extracting the min removes and returns the root (the smallest value), then repairs the heap: the last element is moved to the root position and 'sifted down' — repeatedly swapped with its smaller child — until the heap rule holds again everywhere. Time: O(log n). Space: O(1) extra.
Big-O: Insert/extract O(log n); build O(n).
Min-Heap: Extract Min
Min HeapExtracting the min removes and returns the root (the smallest value), then repairs the heap: the last element is moved to the root position and 'sifted down' — repeatedly swapped with its smaller child — until the heap rule holds again everywhere.
How Extract Min Works
- Save the root value (index 0) — this is the minimum, to be returned.
- Move the last element in the array to the root position.
- Remove the now-duplicate last slot.
- Sift the new root down: compare it with its two children, swap with the smaller child if it's bigger than that child, and repeat until the rule holds.
Extract Min Worked Example
Input: Extract min from [5, 20, 10, 30, 25, 15]
- Save min = 5
- Move last element (15) to the root: [15, 20, 10, 30, 25]
- Compare 15 with children 20 and 10: 10 is smaller and less than 15, swap → [10, 20, 15, 30, 25]
- 15's new children (index 5, 6) don't exist, stop
Output: Removed: 5, heap now: [10, 20, 15, 30, 25]
Press ▶ Run to watch it step by step.
def extract_max(heap):
top = heap[0]
heap[0] = heap.pop() # move last to root
i, n = 0, len(heap)
while True:
l, r, big = 2*i+1, 2*i+2, i
if l < n and heap[l] > heap[big]:
big = l
if r < n and heap[r] > heap[big]:
big = r
if big == i:
break
heap[i], heap[big] = heap[big], heap[i] # sift down
i = big
return top
# O(log n)
# example: extract on [5, 20, 10, 30, 25, 15]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Extract Min Time & Space Complexity
When to Use Extract Min
- Always processing the lowest-cost path next in Dijkstra's algorithm
- Repeatedly pulling the smallest remaining value, as in heap sort (descending)
- Running a 'top-k smallest' style algorithm efficiently
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.