Learn / Heaps and priority queues
Heap implementation
A binary heap is a complete binary tree stored in an array: the children of index i are 2i + 1 and 2i + 2, and every parent is at most (min heap) or at least (max heap) its children. Insert adds at the end and sifts up; removing the top moves the last item to the top and sifts down. Both are O(log n), and building from n values bottom-up is O(n).
How to recognise it
- You need the smallest or largest item again and again while items are added and removed.
- The problem asks you to build, check, repair or convert a heap stored in an array.
- Sorting in place with O(1) extra space and a guaranteed O(n log n).
The picture
As an array this heap is [1, 3, 2, 7, 4, 5]. Read the tree level by level, left to right, and you get the array. The
general idea and the library calls are on the Structures page; this lesson is about writing one
yourself.
| Relation | Index |
|---|---|
parent of i | (i - 1) / 2 |
left child of i | 2i + 1 |
right child of i | 2i + 2 |
| first leaf | n / 2 |
Because the tree is complete (every level full except the last, which fills from the left), the array has no gaps.
Sift up and sift down
- Insert: put the value at the end, then swap it with its parent while it is smaller (for a min heap). Here is the
heap above after inserting
0:
- Remove the top: move the last item to index 0, then swap it with its smaller child while that child is smaller.
- Change a key: set the value, then sift up if it got smaller or down if it got bigger. Only one of the two can move it.
Each sift walks one path from top to bottom, so it costs O(log n).
Building a heap in O(n)
Call sift-down on every non-leaf, from the last one (n / 2 - 1) back to the root. Most nodes are near the bottom and
sink only a step or two, which adds up to O(n), better than n inserts at O(n log n).
Heap sort
Build a max heap. Then swap the top (the maximum) with the last slot, shrink the heap by one and sift the new top down. Repeat. The array ends sorted ascending, in O(n log n) time and O(1) extra space. It is not stable.
Common mistakes
- Using
2iand2i + 1(that is the 1-based layout) with a 0-based array. - Sifting down with the wrong child: in a min heap always pick the smaller one.
- Forgetting that sibling order is free: a heap is not sorted, and many arrays are valid heaps of the same values.
Problems
- Heapify Algorithmmediumguide ready
- Build heap from a given Arraymediumguide ready
- Implement Min Heapmediumguide ready
- Implement Max Heapmediumguide ready
- Check if an array represents a min heapmediumguide ready
- Convert Min Heap to Max Heapmediumguide ready
- Heap Sortmediumguide ready
- Merge 2 Binary Max Heapsmediumguide ready
- Check if a Binary Tree is Heapmediumguide ready
- Convert BST to Min Heapmediumguide ready