Heap properties
easy 16 minA 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).
See it run
A heap is a complete binary tree stored in an array where every parent beats its children; check both rules and watch each operation keep them.
Operations
Navigate by index
Find a node's parent and children in [50, 40, 30, 10, 20, 25, 15] using only arithmetic on the index. No pointers are stored.
Step 1 of 8
Seven values in a list
- 500
- 401
- 302
- 103
- 204
- 255
- 156
This list is a heap. Nothing in it says which value is whose child: the position alone decides.
Step 1: Seven values in a list
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]i = 2print(heap[parent(i)]) # 50print(heap[left(i)]) # 25print(heap[right(i)]) # 15- Time
- O(1)
- Space
- O(1)
- pointer tree
- 3 pointers per node
- array heap
- 0 pointers
Children at 2i + 1 and 2i + 2, parent at (i - 1) // 2. Use // in Python: (i - 1) / 2 gives a float and cannot index a list.
In the real world
The same heap properties doing real jobs. Pick one and step through it.
The old lesson's picture: in a max-heap family, every parent is at least as tall as their children, so the grandparent at the top is the tallest of all.
Step 1 of 4
A family by height
Heights in cm. Grandparent 180 at the top, parents 172 and 168, children 120 and 95 under the first parent. Every parent is taller than their own children.
Step 1: A family by height
family = [180, 172, 168, 120, 95] # max-heap by heightprint(all(family[(i - 1) // 2] >= family[i] for i in range(1, len(family)))) # Trueprint(family[0]) # 180, the tallestCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Thinking a heap is sorted
majorA heap only orders each parent against its children. [5, 10, 15, 20, 25, 18, 30] is a valid min-heap but not sorted (25 comes before 18). Testing for sortedness rejects valid heaps.
Wrongdef is_min_heap(a): return a == sorted(a) # too strictRightdef is_min_heap(a): return all(a[(i - 1) // 2] <= a[i] for i in range(1, len(a)))Using / instead of // for the parent
criticalIn Python, (i - 1) / 2 is a float, and a list cannot be indexed with a float, so it raises TypeError. The parent index needs floor division.
Wrongparent = heap[(i - 1) / 2] # TypeError: float indexRightparent = heap[(i - 1) // 2]Checking only the root
majorThe order rule is on every edge. In [50, 30, 40, 10, 45, 35, 25] the root beats everyone, yet 45 sits below 30. A root-only check says it is a heap.
Wrongdef is_max_heap(a): return all(a[0] >= x for x in a)Rightdef is_max_heap(a): return all(a[(i - 1) // 2] >= a[i] for i in range(1, len(a)))Reading children past the end
majorLeaves have no children. Looping over every index and reading 2i + 1 and 2i + 2 raises IndexError. Loop over parents only and guard the right child.
Wrongfor i in range(n): if a[i] < a[2 * i + 1] or a[i] < a[2 * i + 2]: return FalseRightfor i in range(n // 2): l, r = 2 * i + 1, 2 * i + 2 if a[i] < a[l] or (r < n and a[i] < a[r]): return FalseUsing 1-based formulas on a Python list
criticalChildren 2i and 2i + 1 with parent i // 2 are for heaps that start at index 1. On a 0-based list, index 0 becomes its own left child and every link is off by one.
Wrongleft, right, parent = 2 * i, 2 * i + 1, i // 2Rightleft, right, parent = 2 * i + 1, 2 * i + 2, (i - 1) // 2Expecting heapq to be a max-heap
majorPython's heapq always keeps a min-heap, so heap[0] is the smallest. For a max-heap, push negated values and negate again when you read them.
Wrongheapq.heappush(h, x)largest = h[0] # actually the smallestRightheapq.heappush(h, -x)largest = -h[0]
Interview tips
How to explain it
- Two rules: the shape is a complete binary tree, and every parent is at least (max-heap) or at most (min-heap) its children.
- Stored in an array: children of i at 2i + 1 and 2i + 2, parent at (i - 1) // 2.
- Height floor(log2 n), so peek is O(1) and insert and extract are O(log n).
Spot it in the wild
- Priority queues: schedulers, triage, event simulations.
- Dijkstra and A* pull the closest node from a min-heap.
- Top-k and running medians keep one or two small heaps.
Memory tricks
- HEAP: Highest (or lowest) Element Always at the Peak.
- Double plus one, double plus two; minus one, halve, round down.
- Shape first, order second: append or move last, then sift.
Watch out
- A heap is not sorted, and searching it is O(n).
- Check every edge, not just the root.
- heapq is a min-heap; negate values for a max-heap.