Why building a heap is O(n)
1 A count that does not add up
The last lesson built a heap from a whole array with heapify: sift down every parent, from the last parent back to the root. It also said this takes O(n) time. A quick count says otherwise.
An array of n values has about n/2 parents. One sift down can travel the whole height of the tree, about log n levels. So n/2 sift downs of up to log n swaps each looks like O(n log n). That is the same cost as pushing the n values one at a time.
The quick count is not wrong, but it is loose. It charges every parent the full log n. This lesson finds where that overcounts, shows that the true total is under n swaps, and then measures it.
2 A sift down stops at the bottom
We build a min heap from seven values in falling order, [7, 6, 5, 4, 3, 2, 1]. For a min heap this is the worst case. Every parent is bigger than its children, so every sift down goes as far as it can.
Look at how far each value moved. 5 and 6 started one level above the bottom, so one swap was all they could make. Only 7, at the root, had two levels below it.
A sift down cannot go past the bottom of the tree. So its cost is not log n. It is the node's height: the number of levels between the node and the bottom.
Here is a perfect tree of 15 nodes, each labelled with its height:
| Height | Nodes | Swaps at most |
|---|---|---|
| 0 | 8 | 0 |
| 1 | 4 | 4 |
| 2 | 2 | 4 |
| 3 | 1 | 3 |
| Total | 15 | 11 |
Half the nodes are leaves, and a leaf costs nothing. The quick count charged all 7 parents 3 swaps each, 21 in all. The real worst case is 11, fewer than the 15 nodes.
3 Why the total stays under n
The same table for a heap of a million values looks like this:
| Height | Nodes | Swaps at most |
|---|---|---|
| 0 | 500,000 | 0 |
| 1 | 250,000 | 250,000 |
| 2 | 125,000 | 250,000 |
| 3 | 62,500 | 187,500 |
| 4 | 31,250 | 125,000 |
| 5 | 15,625 | 78,000 |
| 6 to 19 | 15,625 | 109,000 |
| Total | 10⁶ | just under 10⁶ |
Going down the table, each row has half the nodes of the row above. The height grows by only 1. Halving wins, so after row 2 the rows shrink fast.
There is a short way to see the bound for any n. We count the swaps in rounds. In round 1, every node with height at least 1 pays one swap. In round 2, every node with height at least 2 pays one more, and so on. A node of height 3 pays in three rounds, so it pays exactly its height.
In a heap of n values, half the nodes are leaves, so round 1 has at most n/2 nodes. Round 2 has at most n/4, and round 3 at most n/8. Each round has half the nodes of the round before, so the total swaps are at most:
So heapify makes fewer than n swaps, and each swap comes with two comparisons. Heapify runs in O(n) time. It works inside the array, so it needs O(1) extra space.
4 Pushes go the long way
Building with n pushes uses sift up instead. Each new value starts at the bottom and climbs towards the root. So its cost is its depth: the number of levels between the node and the root.
The picture flips. The 8 leaves now pay the most, 3 swaps each. With values in falling order, each new value is the smallest so far, so it climbs all the way to the root.
| Depth | Nodes | Swaps at most |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 2 | 2 |
| 2 | 4 | 8 |
| 3 | 8 | 24 |
| Total | 15 | 34 |
That is 34 swaps against heapify's 11. Sift down gives the many bottom nodes the short trip, and sift up gives them the long one.
At a million values, about half the nodes sit at depth 19. Those leaves alone can cost around 10⁷ swaps, so n pushes take O(n log n).
5 Counting the swaps
The code counts swaps for both builds. heapify is the one from the last lesson, with a counter added. buildByPushes adds each value at the end and sifts it up.
We ran both builds on the values n down to 1, the worst case for both:
| n | heapify | n pushes |
|---|---|---|
| 7 | 4 | 10 |
| 15 | 11 | 34 |
| 10⁵ | just under 10⁵ | about 1.5 × 10⁶ |
| 10⁶ | just under 10⁶ | about 1.8 × 10⁷ |
Heapify stays under n swaps every time. The pushes take about 15 times more at 10⁵ and 18 times more at 10⁶, and the gap keeps growing with log n.
6 Where the O(n) build matters
The fast build helps whenever all the values are there at the start.
- Library heaps. Every language with a heap can build one from a whole collection in O(n), with the same sift-down loop inside.
- Heap sort. It heapifies the array in O(n), then pops n times at O(log n) each. The pops cost more than the build, so the sort is still O(n log n).
- Top k from a full array. Heapify all n values, then pop k times. That costs O(n + k log n), and for small k it is close to O(n).
Here is the one-call build in each language, on [5, 3, 8, 1, 9, 2]:
C++
Range constructor or make_heap. Both build in O(n). Calling push once per value is the O(n log n) way.
Pass the collection to the constructor. It heapifies in O(n). addAll adds the values one at a time, which is O(n log n).
heapify works in place. It changes the list and returns None. Calling heappush once per value is the O(n log n) way.
No heap is built in. Write the heapify from the code above, and call it once on the whole array.
heap.Init is O(n). It works on any type with the five methods container/heap needs, such as MinHeap above. Calling heap.Push once per value is the O(n log n) way.
BinaryHeap::from is O(n). BinaryHeap is a max heap, so Reverse turns it into a min heap. Calling push once per value is the O(n log n) way.
Pass the items to the constructor. Each item is an (element, priority) pair, and the constructor heapifies them in O(n). Calling Enqueue once per value is the O(n log n) way.
7 Mistakes
- Going from the root down. A sift down only works when both subtrees below the node are heaps already. Going from the last parent back to the root makes that true. Going the other way breaks it. On
[4, 3, 2, 1], the root goes first and swaps with 2. Then 3 swaps with 1, but 1 never gets past 2.
- Starting at n − 1. The result is correct, but the first half of the calls are leaves and do nothing. Start at the last parent, n/2 − 1.
- Sift up inside the loop. Sifting up each index from 1 to n − 1 also builds a valid heap. But that is the n pushes build, so it costs O(n log n).
- Calling heap sort O(n). Only the build is O(n). The n pops after it cost O(n log n).
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.