AlgoViz

Heap properties

easy 16 min

A binary heap is a complete binary tree in which every parent is greater than or equal to its children (max-heap) or less than or equal to them (min-heap).

Video lesson · Chapter 1 of 5

A portrait with a rule

0:00 / 4:06

Heap properties — The firefly chandelier

1:27Reel

Read caption

Yara hangs six numbered lanterns in a complete max-heap and checks why the brightest is always at its root. Fill left to right. Let every parent outshine its children.

How it works

Step through the idea, or press Play.

Step 1 of 3

Shape: a complete tree. Every level is full except possibly the last, which fills from the left with no gaps

Understand it

Start here

What a heap is

A binary heap is a binary tree that obeys two rules at once. The shape rule: it is a complete binary tree. The order rule: every parent is at least as big as its children (a max-heap) or at most as big (a min-heap). Together they put the largest or smallest value at the root, where you can read it in O(1)O(1), and they keep the tree so short that adding or removing a value costs only O(log⁡n)O(\log n).

  • Complete shape

    Levels fill top to bottom, left to right. No holes, so it fits in an array.

  • Heap order

    Parent ≥\ge children (max-heap) or parent ≤\le children (min-heap), on every edge.

  • Extreme at the root

    The max or min is always heap[0]: an O(1)O(1) peek.

  • Short and wide

    Height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor: 19 levels for a million values.

Rule 1

Shape: a complete binary tree

A complete binary tree has every level completely filled except possibly the last, and the last level is filled from left to right. A new node may only go into the leftmost free slot of the bottom level; if that level is full, it starts a new level on the far left. Level kk holds at most 2k2^k nodes.

Is this tree complete?

In practice, read the level-order list: if a gap (None) ever appears before a real value, the tree is not complete.

Complete: [10, 5, 3, 4, 1]

  • Root 10, children 5 and 3
  • 4 and 1 fill the bottom level from the left
  • Array has no gaps: 5 slots, 5 values

Not complete: [10, 5, 3, _, 1]

  • Same top two levels
  • Slot 3 (left child of 5) is empty but slot 4 is not
  • The array has a hole, so it is not a heap

Rule 2

Order: max-heap and min-heap

The order rule compares each node only with its own parent. In a max-heap the parent is never smaller; in a min-heap it is never larger. Because this holds on every edge, it chains all the way up: any value is bounded by every ancestor, so the root is the extreme.

The heap-order property (0-based array a)

max-heap: a[parent(i)]≥a[i]min-heap: a[parent(i)]≤a[i]for all 1≤i<n\text{max-heap: } a[\text{parent}(i)] \ge a[i] \qquad \text{min-heap: } a[\text{parent}(i)] \le a[i] \qquad \text{for all } 1 \le i < n
With parent(i)=⌊(i−1)/2⌋\text{parent}(i) = \lfloor (i-1)/2 \rfloor. Equal values are allowed, so [7,7,7][7, 7, 7] is both a max-heap and a min-heap.
PropertyMax-heapMin-heap
Parent and childparent ≥\ge childrenparent ≤\le children
Rootmaximumminimum
Example[10, 5, 3, 4, 1][1, 3, 5, 4, 10]
Peek the rootO(1)O(1)O(1)O(1)
Insert, delete rootO(log⁡n)O(\log n)O(log⁡n)O(\log n)
Typical usemax priority queue, task scheduling by priority, heap sortmin priority queue, Dijkstra's algorithm, event simulation
The two kinds are mirror images: negate every value and a max-heap becomes a min-heap.

By hand

Checking two heaps

Max-heap [10, 5, 3, 4, 1]

  1. 1

    Shape

    Root 10; children 5 and 3; 4 and 1 under 5. The bottom level fills from the left: complete.

  2. 2

    Node 10 (i = 0)

    10≥510 \ge 5 and 10≥310 \ge 3. The root is the maximum.

  3. 3

    Node 5 (i = 1)

    5≥45 \ge 4 and 5≥15 \ge 1.

  4. 4

    Node 3 (i = 2)

    Its children would be at 5 and 6, past n=5n = 5: a leaf, nothing to check. Valid max-heap after 4 comparisons.

Min-heap [1, 3, 5, 4, 10]

  1. 1

    Node 1 (i = 0)

    1≤31 \le 3 and 1≤51 \le 5. The root is the minimum.

  2. 2

    Node 3 (i = 1)

    3≤43 \le 4 and 3≤103 \le 10.

  3. 3

    Node 5 (i = 2)

    A leaf. Valid min-heap: same values as the max-heap, opposite arrangement.

Storage

A tree that lives in an array

Because the tree is complete, you can write its nodes level by level into a list and never leave a gap. The tree is never stored as nodes and pointers: the list is the heap, and parent-child links are pure arithmetic on the index.

Tree positions and array slots: [50, 40, 30, 10, 20, 25, 15]

The array is [50, 40, 30, 10, 20, 25, 15], read straight off the levels: slot 0, then 1 and 2, then 3 to 6.

Index arithmetic (0-based)

left(i)=2i+1,right(i)=2i+2,parent(i)=⌊i−12⌋  (i>0)\text{left}(i) = 2i + 1, \qquad \text{right}(i) = 2i + 2, \qquad \text{parent}(i) = \left\lfloor \frac{i - 1}{2} \right\rfloor \;(i > 0)
For i=2i = 2 (value 30): parent ⌊1/2⌋=0\lfloor 1/2 \rfloor = 0 (50), left 55 (25), right 66 (15). A child index ≥n\ge n means that child does not exist.

Every node of [50, 40, 30, 10, 20, 25, 15]

iValueParent (i - 1) // 2Left 2i + 1Right 2i + 2
050none (root)1: 402: 30
1400: 503: 104: 20
2300: 505: 256: 15
3101: 407: none8: none
4201: 409: none10: none
5252: 3011: none12: none
6152: 3013: none14: none
Slots 3 to 6 are leaves: from ⌊7/2⌋=3\lfloor 7/2 \rfloor = 3 onwards every child index is ≥7\ge 7.

Deep dive

Why the index formulas work

Level kk holds 2k2^k slots and starts at index 2k−12^k - 1 (0, 1, 3, 7, 15, ...), because the levels above it hold 1+2+⋯+2k−1=2k−11 + 2 + \dots + 2^{k-1} = 2^k - 1 nodes. Take the node at position pp within level kk. Its children are positions 2p2p and 2p+12p + 1 of level k+1k + 1, since every node to its left contributes two children first.

Deriving left(i) = 2i + 1

i=2k−1+p  ⇒  left(i)=2k+1−1⏟start of level k+1+2p=2(2k−1+p)+1=2i+1i = 2^k - 1 + p \;\Rightarrow\; \text{left}(i) = \underbrace{2^{k+1} - 1}_{\text{start of level } k+1} + 2p = 2(2^k - 1 + p) + 1 = 2i + 1
The right child is the next slot, 2i+22i + 2. Undo either one to get the parent: ⌊(i−1)/2⌋\lfloor (i - 1)/2 \rfloor maps both 2j+12j + 1 and 2j+22j + 2 back to jj.
Python
def parent(i): return (i - 1) // 2def left(i):   return 2 * i + 1def right(i):  return 2 * i + 2heap = [50, 40, 30, 10, 20, 25, 15]n = len(heap)for i in range(n):    kids = [heap[c] for c in (left(i), right(i)) if c < n]    up = heap[parent(i)] if i else None    print(f"i={i} value={heap[i]} parent={up} children={kids}")assert all(parent(left(i)) == i and parent(right(i)) == i for i in range(1000))
Index helpers, and a check that every child points back to its parent.
Edit and run it in your browser

Why it is fast

Height is floor(log2 n)

In a complete tree of height hh, levels 00 to h−1h - 1 are full and the last level holds between 11 and 2h2^h nodes. That pins nn between two powers of two, and so pins the height.

Height of a heap with n nodes

2h−1⏟full levels+1  ≤  n  ≤  2h+1−1  ⟹  2h≤n<2h+1  ⟹  h=⌊log⁡2n⌋\underbrace{2^h - 1}_{\text{full levels}} + 1 \;\le\; n \;\le\; 2^{h+1} - 1 \;\Longrightarrow\; 2^h \le n < 2^{h+1} \;\Longrightarrow\; h = \lfloor \log_2 n \rfloor
In Python, n.bit_length() - 1 gives the same value without floating-point rounding. See logarithms for why halving gives log⁡2\log_2.
n137815161,0001,000,000
Height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor012334919
The height grows by one only when nn reaches the next power of two.

In code

Validating a heap

is_max_heap(a)

Every parent has a left child, but only some have a right child, so guard it with 2i + 2 < n. For a min-heap, flip the comparisons.
Python
def is_heap(a, kind="max"):    """True if list a satisfies the max-heap (or min-heap) order."""    ok = (lambda p, c: p >= c) if kind == "max" else (lambda p, c: p <= c)    n = len(a)    for i in range(n // 2):                  # parents only        for c in (2 * i + 1, 2 * i + 2):            if c < n and not ok(a[i], a[c]):                return False    return Trueprint(is_heap([10, 5, 3, 4, 1]))                     # Trueprint(is_heap([10, 5, 3, 4, 1], "min"))              # False: 10 > 5print(is_heap([1, 3, 5, 4, 10], "min"))              # Trueprint(is_heap([50, 30, 40, 10, 20, 35, 25]))         # Trueprint(is_heap([50, 30, 40, 10, 45, 35, 25]))         # False: 45 under 30
One function for both kinds. Run it: the examples above plus two broken heaps.
Edit and run it in your browser

What it buys

Operations that keep both rules

Every heap operation follows the same recipe: fix the shape first, then repair the order along one path. Insert appends to the next free slot and sifts the value up; extract moves the last value to the root and sifts it down. The full walkthroughs are in heap operations and heapify.

Shape first, order second

Sift up and sift down each touch at most ⌊log⁡2n⌋\lfloor \log_2 n \rfloor edges. Building bottom-up is O(n)O(n), not O(nlog⁡n)O(n \log n).
OperationTimeWhy
Peek max (or min)O(1)O(1)Always at heap[0]
Insert (push)O(log⁡n)O(\log n)Sift up at most the height
Extract root (pop)O(log⁡n)O(\log n)Sift down at most the height
Build from n valuesO(n)O(n)Most nodes are near the bottom; see heapify
Search for any valueO(n)O(n)The order rule says nothing about left versus right
ValidateO(n)O(n)One comparison per edge
A heap is built for one question, what is the extreme, and answers it in O(1)O(1). It is not a search structure.

Compare

Heap vs binary search tree

Both are binary trees with an ordering rule, but the rules point in different directions. A binary search tree orders left against right (left < node < right), which makes search fast. A heap orders parent against child, which makes the extreme fast and nothing else.

Binary heapBinary search tree (balanced)
Order ruleparent vs childrenleft < node < right
Shapealways completebalanced only with rotations (AVL, red-black)
Storageplain array, no pointersnodes with left and right pointers
Find min or maxO(1)O(1) for one of themO(log⁡n)O(\log n) for both
Search for xO(n)O(n)O(log⁡n)O(\log n)
Insert, deleteO(log⁡n)O(\log n) (delete root only)O(log⁡n)O(\log n) (any key)
Sorted traversalno (needs n pops)yes, in-order in O(n)O(n)
Build from n valuesO(n)O(n)O(nlog⁡n)O(n \log n)
An unbalanced BST can degrade to O(n)O(n) per operation; a heap's shape rule rules that out.

Heap or BST?

Priority queues almost always pick the heap: it is smaller, simpler and cache-friendlier than a balanced tree.

Choosing

Max-heap or min-heap?

  • Max-heap

    Highest priority first, task scheduling, the k smallest values (evict the largest), heap sort in ascending order.

  • Min-heap

    Lowest cost first: Dijkstra, event-driven simulation, merging k sorted lists, the k largest values (evict the smallest).

  • Two heaps

    Running median: a max-heap for the lower half and a min-heap for the upper half.

Which heap for a top-k problem?

The opposite heap keeps the k winners and puts the one to evict at the root. Full worked examples live in priority queues.
Python
import heapqnums = [3, 10, 5, 1, 4]mn = nums[:]heapq.heapify(mn)                  # O(n), min-heap in placeprint(mn[0])                       # 1, the minimummx = [-x for x in nums]heapq.heapify(mx)                  # min-heap of negatives = max-heapprint(-mx[0])                      # 10, the maximumheapq.heappush(mx, -12)print(-heapq.heappop(mx))          # 12
Python's heapq is a min-heap on a plain list. Negate values for a max-heap.
Edit and run it in your browser

Recap

What to remember

HEAP: Highest (or lowest) Element Always at the Peak
  1. 1ShapeComplete binary tree, no holes
  2. 2OrderParent beats children on every edge
  3. 3Array2i + 1, 2i + 2, (i - 1) // 2
  4. 4RootMax or min in O(1)

Shape gives the array and the $\lfloor \log_2 n \rfloor$ height; order gives the root.

Key points

  • A heap is a complete binary tree with the heap-order property: parent ≥\ge children (max-heap) or parent ≤\le children (min-heap).
  • The root holds the maximum (max-heap) or minimum (min-heap), so peek is O(1)O(1).
  • Stored level by level in an array: left 2i+12i + 1, right 2i+22i + 2, parent (i−1)//2(i - 1) // 2; leaves start at ⌊n/2⌋\lfloor n/2 \rfloor.
  • Height is ⌊log⁡2n⌋\lfloor \log_2 n \rfloor, so insert and extract are O(log⁡n)O(\log n); building from a list is O(n)O(n).
  • A heap is not sorted and not a search structure: siblings are unordered and search is O(n)O(n).
  • Validate in O(n)O(n) by checking every parent-child edge; a gap-free array is complete automatically.
  • Use a heap when you repeatedly need the extreme value; use a BST when you need search or sorted order.

Sources