Heaps

The smallest, always on top Β· Part of Trees and graphs

Key idea

Practice

6 questions Β· about 3 min

Explained step by step

Heap

A heap is a complete binary tree with an ordering rule between parents and children. In a min-heap, each parent is less than or equal to its children, so the minimum is at the root. In a max-heap, each parent is greater than or equal, and the maximum is at the root. Unlike a search tree, it doesn't matter whether the left is smaller than the right: only parent and child are compared.

Since a heap is a complete tree, it's stored in an array with no gaps. For the node at index i, the left child is at 2i + 1, the right at 2i + 2 and the parent at (i βˆ’ 1) / 2, rounded down. The root, the maximum or minimum, is the array's first element, and the heap's last element is the rightmost leaf on the last level.

To add a value to a heap, you put it at the end of the array, as a new leaf. That may break the rule, so you sift it up: compare it with its parent and, in a max-heap, if it's larger, swap them. Repeat until the parent is larger or you reach the root. Since the height is about log n, adding costs O(log n).

To remove the root, you don't delete the first element, because everyone would shift. You swap the root with the last element, remove the last, and then sink the new root: compare it with its children and, in a max-heap, swap it with the larger of the 2. Repeat until it's larger than its children or reaches a leaf. It costs O(log n).

Heaps are used mainly for priority queues, where adding and removing cost O(log n). Also for sorting: building a heap and removing the root over and over, the elements come out sorted; that's heap sort. And for finding the k largest of a collection, like the 10 most-read news stories or the 10 best-selling products.

Priority queue

A priority queue is like a queue, but what comes out isn't the first to arrive but the one with the highest priority. Languages come with one ready to use, and it's almost always built with a heap: a max-heap removes the largest first, a min-heap the smallest. Adding and removing cost O(log n), and peeking at the highest priority, O(1).

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

The smallest, always on top