Why building a heap is O(n)

Video lessonComing soon

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.

Heapify on 7, 6, 5, 4, 3, 2, 1
70615243342516i
the array
4637251
Parents: 5 and 6 at height 1, 7 at 2

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:

010201030102010
Each node shows its height. The 8 leaves have height 0
HeightNodesSwaps at most
080
144
224
313
Total1511

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:

HeightNodesSwaps at most
0500,0000
1250,000250,000
2125,000250,000
362,500187,500
431,250125,000
515,62578,000
6 to 1915,625109,000
Total10⁶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.

Counting the 15-node tree in rounds
010201030102010
Round 1: 7 nodes pay one swap each

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:

n/2 + n/4 + n/8 + … ≤ n

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.

323132303231323
Each node shows its depth. The 8 leaves are the deepest

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.

DepthNodesSwaps at most
010
122
248
3824
Total1534

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:

nheapifyn pushes
7410
151134
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.
3124
Root first: 2 sits above 1
4312
Last parent first: a valid heap
  • 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).
When all the values are there at the start, build the heap with one heapify call, not with n pushes.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.