Sub topic 14
Binary heaps: complete tree, heap property, array indices
This chapter assumes you know arrays and 0-based indexing, the idea of a tree with parent and child nodes, Big-O notation, and the priority queue interface from the previous chapter. It covers how a binary heap is shaped, what ordering it guarantees, and how its tree structure maps onto an array. Insert, extract, and bottom-up construction are covered in the chapters that follow.
Why a heap exists
A priority queue must support two operations well: insert an item, and remove the item with the smallest (or largest) key. Two simple implementations both have a slow operation:
- An unsorted array inserts in O(1) but needs O(n) to find the minimum.
- A sorted array finds the minimum in O(1) but needs O(n) to insert, because elements must shift.
A binary heap gives O(log n) for both insert and extract, and O(1) to read the minimum. It does this by keeping the data only partially ordered, which is cheaper to maintain than a full sort.
Two properties define a binary heap
A binary heap is a binary tree that satisfies both of these properties at once.
Shape property: the tree is complete
A binary tree is complete if every level is full except possibly the last, and the last level is filled from left to right with no gaps.
Consider a tree with 6 nodes. Level 0 has 1 node, level 1 has 2, and level 2 has 3 nodes placed in the leftmost positions. That is complete. A tree whose last level has a node in the first and third positions but not the second is not complete.
A complete tree with n nodes has height floor(log2 n). This is the source of the O(log n) bounds, since every operation walks at most one root-to-leaf path.
Order property: the heap property
In a min-heap, every node's key is less than or equal to the keys of its children. In a max-heap, every node's key is greater than or equal to its children's keys.
Two consequences are easy to get wrong:
- The root of a min-heap holds the minimum, and the root of a max-heap holds the maximum.
- There is no ordering between siblings, or between a node and its cousins. In a min-heap, a left child may be larger or smaller than its right sibling. A node in the left subtree may also be larger than a node on a shallower level of the right subtree.
In this example, 5 sits to the left of 3, yet 5 is larger. The heap property only constrains each parent-child pair.
Array representation
Because the tree is complete, no positions are skipped when nodes are numbered level by level, left to right. That numbering is the array order. No pointers are needed, and the structure uses exactly n array cells.
The heap above is stored as:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Key | 2 | 5 | 3 | 9 | 6 | 8 | 4 |
Index formulas
With 0-based indexing, for a node at index i:
| Relation | Formula | Valid when |
|---|---|---|
| Left child | 2i + 1 | 2i + 1 < n |
| Right child | 2i + 2 | 2i + 2 < n |
| Parent | (i - 1) // 2 | i > 0 |
With 1-based indexing, which many textbooks and GATE questions use, the formulas are 2i, 2i + 1, and floor(i / 2). Always check which convention a question uses before computing.
Check with the example: index 1 (key 5) has children at 3 and 4 (keys 9 and 6). Index 5 (key 8) has parent (5 - 1) // 2 = 2 (key 3). Both match the diagram.
Leaves and internal nodes
Indices of the form 2i + 1 must be less than n to exist. A node has at least a left child when 2i + 1 < n, which means i < (n - 1) / 2. So with 0-based indexing:
- The last internal node (the last node with a child) is at index n // 2 - 1.
- The leaves occupy indices n // 2 through n - 1.
- The number of leaves is ceil(n / 2), and the number of internal nodes is floor(n / 2).
For n = 7, the internal nodes are indices 0 to 2 and the leaves are indices 3 to 6. This fact is used when building a heap bottom-up, because leaves are already valid one-node heaps.
Height and level counts
- Node at index i is on level floor(log2(i + 1)) in a 0-based array.
- Level k holds at most 2^k nodes.
- A heap with n nodes has height floor(log2 n).
- A heap of height h has between 2^h and 2^(h+1) - 1 nodes.
For n = 10, the height is 3. Levels 0 to 2 hold 1 + 2 + 4 = 7 nodes, and level 3 holds the remaining 3.
Checking the heap property in code
The array formulas translate directly into a validity check. This function tests a min-heap by comparing every non-root node with its parent.
def is_min_heap(a):
for i in range(1, len(a)):
parent = (i - 1) // 2
if a[parent] > a[i]:
return False
return True
print(is_min_heap([2, 5, 3, 9, 6, 8, 4])) # True
print(is_min_heap([2, 5, 3, 1, 6, 8, 4])) # False: 1 is below 5It is enough to check each node against its parent. Since the property is transitive along every root-to-leaf path, every ancestor is then also no larger than its descendants. The loop runs in O(n) time and uses O(1) extra space.
An empty array and a one-element array both count as valid heaps, and the function returns True for both.
Comparing a heap with related structures
| Structure | Find min | Insert | Extract min | Search for arbitrary key |
|---|---|---|---|---|
| Unsorted array | O(n) | O(1) | O(n) | O(n) |
| Sorted array | O(1) | O(n) | O(1) if sorted descending, else O(n) | O(log n) |
| Min-heap | O(1) | O(log n) | O(log n) | O(n) |
| Balanced BST | O(log n) | O(log n) | O(log n) | O(log n) |
Searching for an arbitrary key in a heap is O(n), because the heap property gives no way to decide between the left and right subtree. The only pruning available is that a subtree whose root already exceeds the target can be skipped in a min-heap.
A heap is not a binary search tree. In a BST, the entire left subtree is smaller than the node, so an in-order traversal yields sorted output. A heap offers no such guarantee.
Where particular values can sit
GATE questions often ask where the maximum or minimum can be located, or how many nodes meet a condition.
- In a min-heap, the maximum is always at a leaf. Any internal node has a child that is at least as large, so an internal node can only be a maximum if it ties with a child. With distinct keys, the maximum is at one of the ceil(n / 2) leaves.
- Finding the maximum in a min-heap therefore takes O(n) time, since you must scan all leaves, which is about n / 2 elements.
- The second smallest key in a min-heap is a child of the root, so it is at index 1 or 2.
- In a max-heap with distinct keys, the third largest is at depth 1 or 2, never deeper.
Worked example: counting nodes
Question. A min-heap has 12 nodes stored in a 0-based array. Which indices are leaves, and what is the parent of index 11?
Solution.
- The last internal node is at n // 2 - 1 = 12 // 2 - 1 = 5.
- Leaves are at indices 6 through 11, which is 6 leaves.
- The parent of index 11 is (11 - 1) // 2 = 5.
- Check: the children of index 5 are 11 and 12. Index 12 does not exist, so node 5 has only a left child. A complete tree allows exactly one such node when n is even.
When n is even, one internal node has a single child. When n is odd, every internal node has two children.
Common errors
- Treating a sorted array as a requirement. A heap's array is generally not sorted.
- Assuming the left child is smaller than the right child. No sibling order exists.
- Using the wrong index base in the child and parent formulas.
- Forgetting the bounds check. The child index 2i + 1 may be at or beyond n, meaning the child does not exist.
- Assuming the minimum of a max-heap is at a specific position other than "some leaf".
- Calling a tree a heap when it is not complete. A tree can satisfy the order property and still fail the shape property, which means it cannot be stored compactly in an array.
Exercise
A max-heap is stored in a 1-based array with 20 elements. (a) Which index holds the parent of the node at index 13? (b) Which indices are the children of the node at index 9? (c) How many leaves does the heap have?
Show answer
(a) The parent is floor(13 / 2) = 6. (b) The children of index 9 would be 2 9 = 18 and 2 9 + 1 = 19, and both are within 20, so they exist. (c) The last internal node is at index floor(20 / 2) = 10, so indices 11 through 20 are leaves. That is 10 leaves, which equals ceil(20 / 2).
Exercise
In a min-heap of 15 distinct keys, in which index range, 0-based, must the largest key be found, and how many comparisons are needed in the worst case to identify it by scanning that range?
Show answer
The maximum must be at a leaf. With n = 15 the leaves are indices 15 // 2 = 7 through 14, which is 8 nodes. Finding the largest among 8 keys takes 7 comparisons.
Exercise
Is the array [1, 3, 2, 6, 5, 4, 7, 9] a valid min-heap? If not, name the first violating index.
Show answer
Check each index against its parent, (i - 1) // 2. Index 1 (3) versus parent index 0 (1): fine. Index 2 (2) versus 1: fine. Index 3 (6) versus parent index 1 (3): fine. Index 4 (5) versus 3: fine. Index 5 (4) versus parent index 2 (2): fine. Index 6 (7) versus 2: fine. Index 7 (9) versus parent index 3 (6): fine. There is no violation, so it is a valid min-heap.