Building a heap

Bottom-up is cheaper · Part of Trees and graphs

Key idea

Practice

6 questions · about 3 min

Explained step by step

Heap

The obvious way to build a heap with n elements is to create an empty one and insert them one at a time: each goes at the end and moves up as needed. Each insertion costs O(log n), so the total is O(n log n). It works, but there's a faster way, because this one treats every element as if it could move all the way up, when most barely move.

The fast way has 2 steps. First, all elements go into the array as they come, even if they break the rule. Then the non-leaf nodes are walked from back to front, sinking each one. The last non-leaf node is the parent of the last element. Since you go bottom-up, when a node is sunk its 2 subtrees are already heaps, and at the end the whole array is.

Sinking from the bottom costs O(n), not O(n log n). The reason is that most nodes are near the bottom and can barely go down. Half are leaves and aren't touched. A quarter sit right above the leaves and go down at most 1 level. An eighth go down at most 2. Only the root can go down log n levels. Adding it all up, the total stays under 2n steps.

To trace it by hand with a small example: the array [1, 5, 3, 9] as a max-heap. There are 4 elements, the last is at index 3 and its parent at 1. Index 1, the 5, is sunk: its child is 9, larger, so they swap and you get [1, 9, 3, 5]. Then index 0, the 1, is sunk: its children are 9 and 3, it swaps with 9 and you get [9, 1, 3, 5]; the 1 still has a larger child, the 5, so it goes down again: [9, 5, 3, 1].

A heap isn't a sorted list: it only guarantees the root is the maximum or minimum, and that each parent beats its children. That's why building it is cheaper than sorting, O(n) against O(n log n). If you only need to keep removing the minimum bit by bit, a heap is enough. If you need everything sorted, you have to remove the root n times, which is O(n log n): heap sort.

Languages come with fast building ready to use. In Python, heapq.heapify turns a list into a min-heap in place, in O(n), sinking bottom-up. In Java, a PriorityQueue can be created from a whole collection. It's worth using them instead of inserting one at a time when you already have all the data: same result with less work.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Bottom-up is cheaper