AlgoViz

Heap operations

medium 18 min

A 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

0:00 / 5:23

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.

Step 1 of 3

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. O(log⁡n)O(\log n).

  • Extract

    Remove the root, move the last value there, then sift down. O(log⁡n)O(\log n).

  • Peek

    Read heap[0] without changing anything. O(1)O(1).

  • 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 ≥\ge 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)

left(i)=2i+1,right(i)=2i+2,parent(i)=⌊i−12⌋\text{left}(i) = 2i + 1, \qquad \text{right}(i) = 2i + 2, \qquad \text{parent}(i) = \left\lfloor \frac{i - 1}{2} \right\rfloor
Max-heap property: A[parent(i)]≥A[i]A[\text{parent}(i)] \ge A[i] for every i≥1i \ge 1. Moving to a parent or child is one multiply or divide, so sifting needs no pointers.

The max-heap [10, 5, 3, 4, 1]

IndexValueParentChildren
010 (root, the max)none5 and 3
150: 104 and 1
230: 10none (55 and 66 are past the end)
341: 5leaf
411: 5leaf
Every parent beats its children: 10>510 > 5, 10>310 > 3, 5>45 > 4, 5>15 > 1. Siblings are not ordered: 3 is smaller than 4 even though it sits higher.

Operation 1

Insert: add at the end, sift up

insert(heap, value)

Appending keeps the tree complete. The new value can only be wrong relative to its parent, so it climbs until its parent is bigger or it reaches the root.

Worked examples (max-heap)

  1. 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); 7>37 > 3, swap: [10, 5, 7, 4, 1, 3]. Parent is now the root 10; 7≤107 \le 10, stop. One swap.

  2. 2

    Insert 12 into [10, 5, 3]

    Append at index 3, under 5. 12>512 > 5, swap: [10, 12, 3, 5]. 12>1012 > 10, swap: [12, 10, 3, 5]. It climbed to the root: the worst case, one swap per level.

  3. 3

    Insert 55 into [50, 30, 40, 10, 20]

    Append at index 5, under 40. 55>4055 > 40, swap: [50, 30, 55, 10, 20, 40]. 55>5055 > 50, swap: [55, 30, 50, 10, 20, 40]. 55 is the new maximum.

Python
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]
Iterative sift up: O(1)O(1) extra space, at most ⌊log⁡2n⌋\lfloor \log_2 n \rfloor swaps.
Edit and run it in your browser

Operation 2

Extract: replace the root, sift down

extract_max(heap)

Removing the last slot keeps the shape. The value moved to the root can only be wrong relative to its children, so it sinks, always swapping with the larger child.

Worked example: extract from [10, 5, 7, 4, 1, 3]

  1. 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. 2

    3 against 5 and 7

    The larger child is 7 and 7>37 > 3: swap, giving [7, 5, 3, 4, 1].

  3. 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

HeapAfter moving the last to the rootSift downResult
[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
Compare with the larger child. If 40 swapped with 30 instead, 30 would sit above 50 and the heap would still be broken.

Operation 3

Peek, size and the empty heap

Peek returns heap[0] and changes nothing, so it is O(1)O(1): 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.

Python
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 range
Peek and extract must both check for emptiness first.
Edit and run it in your browser

Operation 4

Update a key: increase or decrease

update_key(heap, i, new_val) in a max-heap

In a min-heap the directions swap: decrease-key sifts up. That is the decrease-key Dijkstra's algorithm uses.

Worked example on [50, 30, 40, 10, 20]

ChangeRight after the writeSiftResult
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]
Each update walks one path: at most ⌊log⁡2n⌋\lfloor \log_2 n \rfloor swaps.

Operation 5

Delete any element

delete_at(heap, i)

The filler comes from somewhere else in the tree, so it can be too big or too small for its new slot. Check both directions.

Worked example: delete the 10 from [50, 30, 40, 10, 20, 35, 38]

  1. 1

    Fill the hole

    Pop the last value 38 and write it into index 3: [50, 30, 40, 38, 20, 35].

  2. 2

    Too big for its parent

    38 came from the right subtree. Its new parent is 30 and 38>3038 > 30, so sift up: [50, 38, 40, 30, 20, 35].

  3. 3

    Stop

    38≤5038 \le 50. 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 [9,5,7,1][9, 5, 7, 1] and [8,6,2][8, 6, 2]: the joined array [9,5,7,1,8,6,2][9, 5, 7, 1, 8, 6, 2] has 8 under 5, one sift down fixes it, and the merged heap is [9,8,7,1,5,6,2][9, 8, 7, 1, 5, 6, 2].

Heapify versus inserting one by one

Theapify=O(n+m)vsTinserts=∑j=1mO(log⁡(n+j))=O(mlog⁡(n+m))T_{\text{heapify}} = O(n + m) \qquad\text{vs}\qquad T_{\text{inserts}} = \sum_{j=1}^{m} O(\log(n + j)) = O(m \log(n + m))
Heapify wins unless mm is tiny compared with nn. Why heapify is linear is derived in heapify.
Heap typeMerge (meld)InsertExtract-min
Binary heapO(n+m)O(n + m)O(log⁡n)O(\log n)O(log⁡n)O(\log n)
Leftist or skew heapO(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)
Binomial heapO(log⁡n)O(\log n)O(1)O(1) amortisedO(log⁡n)O(\log n)
Fibonacci heapO(1)O(1)O(1)O(1)O(log⁡n)O(\log n) amortised
If your workload merges often, a mergeable heap is the right tool. For everything else the binary heap's simplicity and cache-friendly array win.

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 hh holds between 2h2^h and 2h+1−12^{h+1} - 1 nodes, which pins the height down exactly.

Height of a complete binary tree

2h≤n≤2h+1−1  ⟹  h=⌊log⁡2n⌋  ⟹  Tsift(n)≤c⋅⌊log⁡2n⌋=O(log⁡n)2^h \le n \le 2^{h+1} - 1 \;\Longrightarrow\; h = \lfloor \log_2 n \rfloor \;\Longrightarrow\; T_{\text{sift}}(n) \le c \cdot \lfloor \log_2 n \rfloor = O(\log n)
Sift up makes 1 comparison per level; sift down makes up to 2 (both children). For n=100n = 100, h=6h = 6: at most 6 swaps for insert or extract.
OperationTimeWhyTypical use
InsertO(log⁡n)O(\log n)Sift up through at most the heightAdd a task, stream in data, event scheduling
Extract max/minO(log⁡n)O(\log n)Sift down through at most the heightProcess the top priority, Dijkstra, heap sort
PeekO(1)O(1)Read heap[0]Check the next task, monitor the min/max
Update keyO(log⁡n)O(\log n)One sift up or down (plus finding the index)Dijkstra and Prim decrease-key
Delete at indexO(log⁡n)O(\log n)Fill with last, one siftCancel a job
Build from n valuesO(n)O(n)Bottom-up heapifyStart from a batch
Merge (binary heap)O(n+m)O(n + m)Concatenate and heapifyCombine two queues
Search for a valueO(n)O(n)No order between siblingsAvoid: keep an index map
Extra space for each operation is O(1)O(1) with iterative sifts. A recursive sift uses O(log⁡n)O(\log n) stack frames.

In Python

The heapq API and the negation trick

heapq works on a plain list, as a min-heap

CallDoesTime
heapq.heappush(h, x)Insert x (append, sift up)O(log⁡n)O(\log n)
heapq.heappop(h)Remove and return the smallestO(log⁡n)O(\log n)
h[0]Peek at the smallestO(1)O(1)
heapq.heapify(h)Turn a list into a heap in placeO(n)O(n)
heapq.heappushpop(h, x)Push x, then pop the smallest (faster than both)O(log⁡n)O(\log n)
heapq.heapreplace(h, x)Pop the smallest, then push xO(log⁡n)O(\log n)
heapq.nlargest(k, xs) / nsmallestTop k without sorting everythingO(nlog⁡k)O(n \log k)
heapq.merge(*sorted_iters)Lazily merge sorted inputsO(Nlog⁡k)O(N \log k)
There is no update-key or delete in heapq; use lazy deletion or write your own sifts.
Python
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, lunch
Max-heap by negation, and tuples for priorities with a tie-breaker.
Edit and run it in your browser

Do

  • 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 heappushpop or heapreplace for the size-k pattern: one sift instead of two.
  • Call heapify once on a batch instead of pushing n times.

Avoid

  • Expecting heappop to return the largest value.
  • Calling h.sort(), h.remove() or h.insert(0, x) and still treating h as 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?

The counter-intuitive part: to keep the largest values you use a min-heap, because the root is the weakest member and the one to evict.
Python
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]
Stream of scores, k = 3: O(nlog⁡k)O(n \log k) time, O(k)O(k) space.
Edit and run it in your browser
  • K-th largest

    Size-kk min-heap; the root is the answer. O(nlog⁡k)O(n \log k).

  • Top k frequent

    Count with a dictionary, then keep a size-kk heap of (count, item).

  • Merge k sorted lists

    Heap of the kk list heads; pop the smallest, push its successor. O(Nlog⁡k)O(N \log k).

  • 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 O(1)O(1); insert, extract, update and delete are O(log⁡n)O(\log n) because h=⌊log⁡2n⌋h = \lfloor \log_2 n \rfloor.
  • 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 O(n+m)O(n + m).
  • Python's heapq is 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 kk: O(nlog⁡k)O(n \log k) time, O(k)O(k) space.

Sources