Heap operations
medium 18 minA binary heap supports insert (add at the end, sift up), extract (move the last value to the root, sift down) and peek (read the root).
Video lesson · Chapter 1 of 6
A newcomer takes the lead
Heap insert, extract and peek — The meteor on the scale
1:26Reel
Read caption
Nia inserts a new record meteor, peeks at the root, then extracts it and repairs the remaining max-heap. Arrive at the end and climb. Leave from the root and sink.
How it works
Step through the idea, or press Play.
Insert at the end, sift up. The new value takes the next free slot so the tree stays complete, then swaps with its parent while it is bigger
Understand it
Start here
What heap operations are
A binary heap keeps the most important value at the front and everything else only loosely ordered. That loose order is cheap to maintain: every operation is a small edit at the root or the end of the array, followed by one walk along a single path. Think of a VIP line: the most important guest is always at the front, a new arrival joins at the back and moves up past anyone less important, and when the front guest is served, the next most important takes their place.
Insert
Add at the end of the array, then sift up. .
Extract
Remove the root, move the last value there, then sift down. .
Peek
Read
heap[0]without changing anything. .Update, delete, merge
Change a key, remove any slot, or join two heaps, all built from the same two sifts.
Foundations
The heap behind the operations
In a max-heap every parent is its children, so the root is the maximum; a min-heap flips the comparison. The tree is complete, so it packs into a plain array with no pointers. The full story is in heap properties; here is what the operations rely on.
Index arithmetic (0-based)
The max-heap [10, 5, 3, 4, 1]
| Index | Value | Parent | Children |
|---|---|---|---|
| 0 | 10 (root, the max) | none | 5 and 3 |
| 1 | 5 | 0: 10 | 4 and 1 |
| 2 | 3 | 0: 10 | none ( and are past the end) |
| 3 | 4 | 1: 5 | leaf |
| 4 | 1 | 1: 5 | leaf |
Operation 1
Insert: add at the end, sift up
insert(heap, value)
Worked examples (max-heap)
- 1
Insert 7 into [10, 5, 3, 4, 1]
Append at index 5:
[10, 5, 3, 4, 1, 7]. Parent is index 2 (value 3); , swap:[10, 5, 7, 4, 1, 3]. Parent is now the root 10; , stop. One swap. - 2
Insert 12 into [10, 5, 3]
Append at index 3, under 5. , swap:
[10, 12, 3, 5]. , swap:[12, 10, 3, 5]. It climbed to the root: the worst case, one swap per level. - 3
Insert 55 into [50, 30, 40, 10, 20]
Append at index 5, under 40. , swap:
[50, 30, 55, 10, 20, 40]. , swap:[55, 30, 50, 10, 20, 40]. 55 is the new maximum.
def insert(heap, value): heap.append(value) i = len(heap) - 1 while i > 0: parent = (i - 1) // 2 if heap[i] <= heap[parent]: break heap[i], heap[parent] = heap[parent], heap[i] i = parenth = [10, 5, 3, 4, 1]insert(h, 7)print(h) # [10, 5, 7, 4, 1, 3]h = [50, 30, 40, 10, 20]insert(h, 55)print(h) # [55, 30, 50, 10, 20, 40]Operation 2
Extract: replace the root, sift down
extract_max(heap)
Worked example: extract from [10, 5, 7, 4, 1, 3]
- 1
Save and replace
Keep
top = 10. Pop the last value 3 and write it into the root:[3, 5, 7, 4, 1]. Size is now 5. - 2
3 against 5 and 7
The larger child is 7 and : swap, giving
[7, 5, 3, 4, 1]. - 3
Stop
3 is at index 2, whose children would be 5 and 6, both past the end. Return 10; the heap is
[7, 5, 3, 4, 1].
Two more extractions
| Heap | After moving the last to the root | Sift down | Result |
|---|---|---|---|
| [10, 7, 5, 4, 1, 3] | [3, 7, 5, 4, 1] | 3 sinks below 7, then below 4 | [7, 4, 5, 3, 1], returns 10 |
| [55, 30, 50, 10, 20, 40] | [40, 30, 50, 10, 20] | 40 sinks below 50, then is a leaf | [50, 30, 40, 10, 20], returns 55 |
Operation 3
Peek, size and the empty heap
Peek returns heap[0] and changes nothing, so it is : the heap property already did the work of putting the maximum there. Size and is-empty are just len(heap). The one thing to guard is the empty heap: there is no root to read or remove.
import heapqh = [1, 3, 4, 5, 7] # already a min-heapprint(h[0]) # peek: 1, nothing movesprint(len(h)) # size: 5empty = []print(empty[0] if empty else None) # guarded peek: Nonetry: heapq.heappop(empty)except IndexError as e: print("IndexError:", e) # index out of rangeOperation 4
Update a key: increase or decrease
update_key(heap, i, new_val) in a max-heap
Worked example on [50, 30, 40, 10, 20]
| Change | Right after the write | Sift | Result |
|---|---|---|---|
| index 3: 10 → 60 | [50, 30, 40, 60, 20] | up: swap with 30, then with 50 | [60, 50, 40, 30, 20] |
| index 0: 60 → 15 | [15, 50, 40, 30, 20] | down: swap with 50, then with 30 | [50, 30, 40, 15, 20] |
Operation 5
Delete any element
delete_at(heap, i)
Worked example: delete the 10 from [50, 30, 40, 10, 20, 35, 38]
- 1
Fill the hole
Pop the last value 38 and write it into index 3:
[50, 30, 40, 38, 20, 35]. - 2
Too big for its parent
38 came from the right subtree. Its new parent is 30 and , so sift up:
[50, 38, 40, 30, 20, 35]. - 3
Stop
. One swap, and it went upwards, which is why a delete that only sifts down is a bug.
Operation 6
Merge two heaps
A binary heap has no clever merge. Concatenate the two arrays and run bottom-up heapify on the result. For heaps and : the joined array has 8 under 5, one sift down fixes it, and the merged heap is .
Heapify versus inserting one by one
| Heap type | Merge (meld) | Insert | Extract-min |
|---|---|---|---|
| Binary heap | |||
| Leftist or skew heap | |||
| Binomial heap | amortised | ||
| Fibonacci heap | amortised |
Complexity
Why the cost is O(log n)
Every sift moves one level per swap, so its cost is bounded by the height of the tree. A complete binary tree of height holds between and nodes, which pins the height down exactly.
Height of a complete binary tree
| Operation | Time | Why | Typical use |
|---|---|---|---|
| Insert | Sift up through at most the height | Add a task, stream in data, event scheduling | |
| Extract max/min | Sift down through at most the height | Process the top priority, Dijkstra, heap sort | |
| Peek | Read heap[0] | Check the next task, monitor the min/max | |
| Update key | One sift up or down (plus finding the index) | Dijkstra and Prim decrease-key | |
| Delete at index | Fill with last, one sift | Cancel a job | |
| Build from n values | Bottom-up heapify | Start from a batch | |
| Merge (binary heap) | Concatenate and heapify | Combine two queues | |
| Search for a value | No order between siblings | Avoid: keep an index map |
In Python
The heapq API and the negation trick
heapq works on a plain list, as a min-heap
| Call | Does | Time |
|---|---|---|
heapq.heappush(h, x) | Insert x (append, sift up) | |
heapq.heappop(h) | Remove and return the smallest | |
h[0] | Peek at the smallest | |
heapq.heapify(h) | Turn a list into a heap in place | |
heapq.heappushpop(h, x) | Push x, then pop the smallest (faster than both) | |
heapq.heapreplace(h, x) | Pop the smallest, then push x | |
heapq.nlargest(k, xs) / nsmallest | Top k without sorting everything | |
heapq.merge(*sorted_iters) | Lazily merge sorted inputs |
import heapqnums = [3, 1, 4, 1, 5]h = [-x for x in nums]heapq.heapify(h)print(-h[0]) # peek max: 5print(-heapq.heappop(h)) # pop max: 5heapq.heappush(h, -9)print(-h[0]) # 9# (priority, counter, task): the counter breaks ties so tasks are never comparedtasks, count = [], 0for prio, name in [(2, "email"), (1, "deploy"), (2, "lunch")]: heapq.heappush(tasks, (prio, count, name)); count += 1while tasks: print(heapq.heappop(tasks)[2]) # deploy, email, lunchDo
- Negate numbers going in and coming out to get a max-heap.
- Push
(priority, counter, item)tuples so equal priorities never compare the items. - Use
heappushpoporheapreplacefor the size-k pattern: one sift instead of two. - Call
heapifyonce on a batch instead of pushing n times.
Avoid
- Expecting
heappopto return the largest value. - Calling
h.sort(),h.remove()orh.insert(0, x)and still treatinghas a heap. - Reading
h[-1]as the maximum of a min-heap: the last slot is just some leaf. - Negating strings or objects: wrap them or use a key tuple instead.
Pattern
Top-k and the k-th largest
Which heap for a top-k question?
import heapqdef kth_largest(stream, k): heap = [] for x in stream: if len(heap) < k: heapq.heappush(heap, x) elif x > heap[0]: heapq.heapreplace(heap, x) return heap[0]print(kth_largest([5, 12, 3, 9, 15, 8], 3)) # 9print(heapq.nlargest(3, [5, 12, 3, 9, 15, 8])) # [15, 12, 9]K-th largest
Size- min-heap; the root is the answer. .
Top k frequent
Count with a dictionary, then keep a size- heap of (count, item).
Merge k sorted lists
Heap of the list heads; pop the smallest, push its successor. .
Running median
A max-heap for the lower half and a min-heap for the upper half, kept balanced.
Recap
Key takeaways
Key points
- Insert: append, then sift up while bigger than the parent. Extract: save the root, move the last value to the root, sift down with the larger child.
- Peek is ; insert, extract, update and delete are because .
- Update key: more important means sift up, less important means sift down. Delete fills the hole with the last value and checks both directions.
- Merge binary heaps by concatenating and heapifying in .
- Python's
heapqis a min-heap on a list: negate for a max-heap, use tuples with a counter for priorities. - Top-k largest uses a min-heap of size : time, space.