Best on a larger screen — the animation and controls have more room to breathe.
Inputs

Heaps

A heap is a complete binary tree that keeps one invariant, the heap property: no child outranks its parent (a parent is ≤ its children in a min-heap, and ≥ them in a max-heap). That rule pins the extremum to the root, so peek costs O(1) while insert and extract_top cost O(log n), with the tree stored in a plain array.

Think of a heap as an org chart with one rule: nobody may outrank their boss. The root is guaranteed to hold the top rank, while peers on any row can appear in any order.

How a Heap Works

The tree is implicit. The node at array index i keeps its children at 2i + 1 and 2i + 2, and its parent at (i − 1) // 2. Completeness (every level full except possibly the last, filled left to right) ensures the array has no holes, so index arithmetic reconstructs the hierarchy without node objects or pointers.

A heap supports three core operations:

peek reads data[0] without modifying the heap. The root is the answer by construction.

insert appends the new value at the end of the array (the next free slot in the bottom row), then sifts up: while the newcomer beats its parent (smaller in a min-heap), the two swap and the newcomer climbs one level. The loop ends when the newcomer reaches index 0 or meets a parent it does not beat.

extract_top cannot delete the root directly, because that would tear a hole in a tree that must stay complete. Instead, the implementation saves data[0] as the return value, pops the last element off the array (the one node a complete tree can remove without creating a gap), drops it into slot 0, and sifts down. At each level, it finds the better of the two children (the smaller in a min-heap), swaps if that child beats the current node, and descends into that subtree, stopping when neither child wins or no children remain.

One detail to watch during sift-down: the algorithm compares against the best child only. It checks both children first (left, then right) before swapping, and on a tie the left child stays chosen because the right wins only on a strict comparison.

The visualization runs the same code as a min-heap or a max-heap, differing only in the comparator (< versus >). It shows the structure twice at once, tree above and array below, both moved by the same swaps so index arithmetic and tree shape stay aligned.

Heaps Step by Step

The default demo starts with a min-heap (capacity slider at 10) pre-loaded with the trace insert 5, insert 3, insert 8, insert 1, insert 9, insert 2, extractTop. Press Play to watch the full run, or step through each operation yourself from an empty heap.

insert(5) lands at index 0. The sift-up loop does not run because i > 0 is already false, so the heap is [5] and the root settles immediately.

insert(3) is appended at index 1, then compared with its parent at index 0: 3 < 5 violates the heap property, so arr[1] ↔ arr[0] swap. Heap: [3, 5].

insert(8) is appended at index 2, whose parent is index 0. Because 8 ≥ 3, the rule already holds and the loop exits with no swap. Heap: [3, 5, 8].

insert(1) climbs all the way to the root. Appended at index 3 with parent index 1, 1 < 5 swaps arr[3] ↔ arr[1], giving [3, 1, 8, 5]. Now at index 1 with parent index 0, 1 < 3 swaps arr[1] ↔ arr[0], giving [1, 3, 8, 5]. Reaching index 0 ends the loop after two comparisons and two swaps.

insert(9) and insert(2) repeat the pattern. 9 lands at index 4, loses its one comparison against parent 3, and settles: [1, 3, 8, 5, 9]. 2 lands at index 5, beats parent 8 (swap arr[5] ↔ arr[2]), then loses to root 1 and settles at index 2: [1, 3, 2, 5, 9, 8]. As a tree: root 1, children 3 and 2; under 3 sit 5 and 9; under 2 sits 8 alone.

extract_top() returns 1. The root lifts out, and the last element (8 at index 5) moves into slot 0, shrinking the array to [8, 3, 2, 5, 9]. Sift-down at index 0 checks children 3 (left) and 2 (right): the smaller is 2, and 2 < 8, so arr[0] ↔ arr[2] swap to give [2, 3, 8, 5, 9]. Descending to index 2, its left child would sit at index 5, past the end, so 8 is a leaf and the sift settles. The new top is 2, the second-smallest value.

In the animation, the tree view leads and the array row mirrors it underneath. Each comparison draws a dashed arc between the two contestants labeled with the comparison; on a sift-down, the chosen child gets its own color before any motion happens. Swapping nodes glide past each other in both views at once, the inserted node flashes green when it settles, and an extracted root lifts off the top.

Time and Space Complexity

OperationComplexity
insertO(log n)
extract_topO(log n)
peekO(1)
SpaceO(n)

The logarithm is the tree's height: a complete binary tree with n nodes is ⌈log₂(n+1)⌉ levels tall, and a sift moves one level per swap, so the sift work in both mutating operations is bounded by the height (about 20 levels for a million elements). The growable backing array occasionally resizes, copying O(n) references once, so across many operations each mutation stays amortized O(log n). Space is the bare array, with zero pointer overhead. Building a heap from n existing items by sifting down from the last internal node runs in O(n) time rather than O(n log n), because most nodes sit near the bottom with few levels below them.

Edge Cases

  • Empty heap. peek returns None; extract_top raises an underflow. The buttons stay enabled on an empty heap so you can watch the error path execute.
  • Single element. extract_top pops the only entry and the if self.data: guard fails afterward, so moving the last element to the root and sifting down never run. The code highlight shows the guard alone.
  • Duplicates and ties. Heaps allow equal values; the property is ≤, not <. In this implementation a tied right child never displaces the left, so equal siblings leave the left as the swap target.
  • Visualization capacity cap (4–15, default 10). The capacity slider is a display limit to keep the tree legible on the canvas rather than a heap property. Real heaps grow without bound; inserting past the cap prints a status line noting that it is only a view limit.

Common Mistakes

  • Treating the array as sorted. An array-backed heap is not sorted. After the trace above, the array reads [2, 3, 8, 5, 9], with 8 before 5. Left to right stores the tree level by level rather than by rank; sorted output comes from extracting repeatedly, which is heap sort.
  • Sifting down toward the wrong child. Swapping with the larger child of a min-heap plants a violation directly beneath the node you just moved. Pick the best child first, then compare, then swap.
  • Botching the index math. Zero-indexed heaps place children at 2i + 1 and 2i + 2 and parents at (i − 1) // 2. The 1-indexed variant (2i, 2i + 1, i // 2) is also common, and mixing the two conventions silently corrupts parent-child links.
  • Expecting fast arbitrary search. A heap cannot find an arbitrary value faster than O(n), because the heap property says nothing about where a non-extremal element lives. For key lookup or listing elements in order, use a balanced BST; use a heap when you only need the extremum.
  • Flipping the comparator casually. Min versus max is one < versus >. Flipping it leaves the heap internally valid while upside down, so callers expecting the other ordering break silently.

A few lessons that share the same technique or lead into the next idea.

Premium players need paid access. Every Explain doc is free.

Browse topic

Embed this lesson in a blog, docs, or course?

Found a mistake or something unclear?