A heap is a special type of tree-based data structure that allows us to quickly access the element with the highest priority.
In this chapter, we'll explore what a heap is, how it works, the difference between min-heaps and max-heaps, and how to implement the common heap operations. We'll also discuss their time complexities and when to use heaps to solve problems efficiently.
A binary heap allows us to insert and remove elements in O(log n) time, while accessing the highest-priority element in O(1) time.
What "highest priority" means depends on the problem. It could be the smallest value, the largest value, or even the task with the earliest deadline.
This makes heaps especially useful when we need to repeatedly find and process the most important element. You'll see heaps in:
A heap keeps either the smallest or the largest element at the top, where we can read it in constant time. In this chapter, we'll focus on binary heaps, which are the most common kind.
A binary heap is a complete binary tree that follows a special rule called the heap property. Here's the min-heap we'll use as our running example:
Let's look at both rules.
A complete binary tree means that every level is completely filled, except possibly the last level, which is filled from left to right.
In the tree above, the first two levels are full. The last level has two nodes, 9 and 7, and they sit in the leftmost positions with no gaps between them.
This structure is important for two reasons:
The heap property determines how each parent compares to its children. Based on this property, we have two types of heaps: min-heap and max-heap.
In a min-heap, every parent is less than or equal to its children.
This ensures that the smallest element is always at the root, allowing us to access it in O(1) time. In the tree above, 2 is smaller than its children 5 and 4, and 5 is smaller than its children 9 and 7.
A max-heap works the other way around. Every parent is greater than or equal to its children, so the largest element is always at the root.
This means we can also access the maximum in O(1) time.
Notice that both trees hold the same five values. Only the order changes.
The heap property only compares a parent with its children. It says nothing about siblings, and nothing about nodes on different branches. In the min-heap above, 4 at index 2 is smaller than 9 at index 3, even though 9 sits on a lower level. That's allowed. A heap is not a sorted array; it only guarantees that the smallest (or largest) element is at the root.
For the rest of this chapter, we'll use a min-heap to explain and implement the core operations. The same logic applies to a max-heap. We just need to reverse the comparisons so that larger values move toward the root instead of smaller ones.
Even though we visualize a heap as a tree, in practice, we usually store it in a simple array.
This is possible because a heap is a complete binary tree, meaning we can store its nodes level by level without leaving any gaps:
Here is our min-heap with the array index shown on each node:
As an array, it is [2, 5, 4, 9, 7].
With this arrangement, we can easily navigate between parents and children using simple formulas. For any node at index i:
2 * i + 1.2 * i + 2.(i - 1) / 2, rounded down.Let's check these on our heap. The node at index 1 holds 5. Its left child is at index 2 × 1 + 1 = 3, which holds 9, and its right child is at index 2 × 1 + 2 = 4, which holds 7. Going the other way, the parent of index 1 is at (1 − 1) / 2 = 0, the root.
This way, we can represent the entire tree using a simple array, without needing any pointers or additional references between nodes.
In code, we store the heap in a resizable array, such as an ArrayList in Java, and add the three helper formulas:
The array grows and shrinks at its end as we add and remove elements, which is exactly where a complete binary tree gains and loses its last node. The sections below add the core heap operations to this class.
Let's now look at the core heap operations, starting with insertion.
To insert a new element into a min-heap, we first add it to the end of the array, which represents the next available position in the tree. This ensures that the tree remains complete.
However, there's a problem. The new element might be smaller than its parent, which would violate the min-heap property.
To fix this, we use a process called sift up, also known as bubble up:
Notice that we only need to check the path from the newly inserted element to the root. The rest of the heap already satisfies the heap property, so we don't need to touch it.
Let's walk through an example. Suppose we have this min-heap, [2, 5, 4, 9, 7], and want to insert the value 1.
We start by adding 1 at the end of the array, at index 5. The array is now [2, 5, 4, 9, 7, 1].
Its parent is at index (5 − 1) / 2 = 2, which contains 4. Since 1 is smaller than 4, we swap them. The array becomes [2, 5, 1, 9, 7, 4].
Now, 1 is at index 2, and its new parent is the root at index 0, which contains 2. Again, 1 is smaller, so we swap them. The array becomes [1, 5, 2, 9, 7, 4].
Since 1 has reached the root, we're done. The min-heap property is restored, 1 is now the smallest element at the root, and the tree is still complete.
Now, let's see how to implement this in code.
i to its index.i is greater than zero, we calculate the parent index as (i - 1) / 2 using integer division.i to the parent's index, and repeat the process.This continues until the element reaches its correct position.
Since a complete binary tree has a height of O(log n), the new element can move upward through at most O(log n) levels. Therefore, insertion takes O(log n) time in the worst case. It uses O(1) extra space, because the swaps happen in place.
Next, let's look at the extract minimum operation, which removes and returns the smallest element from a min-heap.
Since the smallest element is always at the root, we know exactly which value to remove. But we can't simply delete the root, because that would leave a gap at the top of the tree.
So here's what we do instead:
This keeps the tree complete, but there's a problem. The new root might be larger than its children, which would violate the min-heap property.
To fix this, we use a process called sift down, also known as bubble down:
We keep moving the element downward until it's smaller than or equal to both children, or it reaches a leaf. At that point, the min-heap property is restored, and we're done.
Why the smaller child? After the swap, that child becomes the parent of the other one. Moving the smaller child up guarantees it is less than or equal to its former sibling, so the new parent is valid on both sides.
Let's walk through another example, using the heap we got from the insert walkthrough: [1, 5, 2, 9, 7, 4].
First, we save the root value, 1, since that's the minimum element we want to return.
Then, we move the last element, 4, to the root and remove the last slot. The array is now [4, 5, 2, 9, 7].
Now, we need to restore the min-heap property. The root contains 4, and its two children are 5 and 2. We compare the children and choose the smaller one, which is 2. Since 2 is smaller than 4, we swap them. The array becomes [2, 5, 4, 9, 7].
Now, 4 is at index 2. Its left child would be at index 2 × 2 + 1 = 5, which is outside the array, because the heap now has only 5 elements (indices 0 to 4). So it has no children, and we can stop.
The min-heap property is restored, 2 is now the smallest element at the root, and we've successfully removed the previous minimum, 1. We're also back to the heap we started the insert walkthrough with.
Now, let's see how to implement this in code.
The extractMin method first checks whether the heap is empty. If it is, we throw an exception because there's nothing to remove.
Otherwise, we save the root value in a variable called minimum and remove the last element from the array. If the heap is now empty, that means it only contained one element, so we can simply return minimum.
Otherwise, we move the last element to the root and call siftDown to restore the heap property.
Inside siftDown:
smallest to point to that child.smallest is still the current index, the heap property is satisfied, so we stop.This continues until the element reaches its correct position.
Since sift down can move through at most the height of the heap, extractMin takes O(log n) time in the worst case.
Next, let's look at peek, which is the simplest heap operation.
Suppose we want to find the smallest element in a min-heap without removing it. Since the smallest element is always at the root, we simply return the value at index 0.
That's all we need to do. There's no swapping, no sifting, and no modification to the heap. Like extractMin, we only need to guard against an empty heap.
And because accessing an array element takes constant time, peek runs in O(1) time.
Now, suppose we have an unsorted array and want to turn it into a heap.
One approach is to start with an empty heap and insert each element one by one. This works, but it takes O(n log n) time in the worst case, because each of the n inserts can cost O(log n).
Fortunately, there's a more efficient approach called bottom-up heap construction, or simply heapify, which takes just O(n) time.
Here's how it works. Instead of inserting elements one at a time, we build the heap from the bottom up:
n / 2 - 1, using integer division.siftDown on each node.We're processing nodes from the bottom up, which means that by the time we reach a node, both of its child subtrees are already valid heaps. So we only need to move the current element down to its correct position. We repeat this process until we reach the root.
Let's walk through an example using this unsorted array: [9, 5, 4, 2, 7, 1].
We have six elements, so the last non-leaf node is at index 6 / 2 − 1 = 2.
At index 2, we have 4, and its only child is 1. Since 1 is smaller than 4, we swap them. The array becomes [9, 5, 1, 2, 7, 4].
Next, we move to index 1, which contains 5. Its children are 2 and 7. Since 2 is the smaller child, we swap it with 5. The array becomes [9, 2, 1, 5, 7, 4].
Finally, we reach the root at index 0. The root contains 9, and its children are 2 and 1. We choose the smaller child, 1, and swap it with 9. The array becomes [1, 2, 9, 5, 7, 4].
Now, 9 is at index 2, where it has one child, 4. Since 4 is smaller than 9, we swap them again. The array becomes [1, 2, 4, 5, 7, 9].
And that's it! The entire array now satisfies the min-heap property.
Notice that the root's siftDown took two swaps. That is the sift down from the extract-min section at work: the element keeps moving until it settles, not just one level.
Now, let's see how to implement this in code.
First, we copy the input values into our heap array. Then, starting from the last non-leaf node, we move backward toward the root, calling siftDown at each position. Once the loop finishes, our heap is ready.
And if we're allowed to modify the original array, we can perform this process directly on it without creating a separate array. That brings the extra space down to O(1).
Now, let's understand why bottom-up heap construction takes O(n) time.
At first, this might seem surprising, because a single siftDown operation can take O(log n) time, and we call it about n / 2 times. So why doesn't building the entire heap take O(n log n)?
The key is that most nodes don't need to move very far.
Think about the structure of a complete binary tree:
Only a few nodes near the root might need to move all the way down the tree.
Here's what that looks like for a full tree with 15 nodes:
The total work is 11 moves, which is less than n = 15. This means most nodes require very little work, while only a small number need more expensive operations.
When we add up the work across all nodes, the total turns out to be O(n), rather than O(n log n). In general, the sum is about n/4 × 1 + n/8 × 2 + n/16 × 3 + ..., and this series adds up to less than n.
And that's why building a heap from the bottom up takes linear time, making it more efficient in the worst case than inserting all the elements one by one.
In practice, you usually don't need to implement a heap from scratch, because most programming languages already provide built-in support for it. These are usually exposed as a priority queue: a collection that always hands out its highest-priority element next. A binary heap is the most common way to implement one, so you get the same complexities: O(log n) to add or remove, and O(1) to peek.
In Java, we have PriorityQueue, which behaves like a min-heap by default.
In Python, the heapq module provides min-heap operations on a regular list. For numeric values, a common way to get max-heap behavior is to insert negative values and negate them again when removing them.
And in C++, priority_queue behaves like a max-heap by default.
So while the default behavior and syntax vary across languages, the core idea remains the same. We want to efficiently keep track of the highest-priority element without having to search through the entire collection every time.
Picking the wrong default is one of the most common bugs in heap-based interview answers, so check it for your language. Java, Python, and C# give you a min-heap, while C++ and Rust give you a max-heap. Go's container/heap follows whatever your Less method says, and the example below makes it a min-heap.
Java's PriorityQueue<E> is a min-heap by default. To turn it into a max-heap, pass a reverse-order comparator.
Now that we understand how heaps work, let's look at when we should use them. There are a few common patterns worth recognizing.
The first is Top K or Bottom K problems, where we need to keep track of the K largest or smallest elements.
For example, suppose we want to find the K largest values from a stream of numbers. We can maintain a min-heap of size K.
The smallest value among our current K elements stays at the root. Whenever a larger value arrives, we can replace the root and restore the heap property. Each new value costs O(log K), so a stream of n values takes O(n log K) time and O(K) space.
For example, with K = 3, after seeing 5, 1, 8, and 3, the heap holds the three largest values [3, 5, 8], with 3 at the root. When 4 arrives, it is larger than 3, so 4 replaces the root and sifts down. The heap now holds [4, 5, 8].
Another common use case is merging K sorted lists.
We can add the first element from each list to a min-heap. Each time we remove the smallest element, we add the next element from the same list. By repeating this process, we can efficiently merge all the lists into sorted order.
The heap never holds more than K elements, so each step costs O(log K). Merging N elements in total takes O(N log K) time.
Heaps are also useful in task scheduling and simulations, where we repeatedly need to find the next task or event to process. If each event is keyed by its time, a min-heap always has the earliest event at the root.
You'll also encounter them in shortest-path algorithms, such as Dijkstra's algorithm, where a min-heap helps us efficiently select the node with the smallest tentative distance.
Whenever a problem requires you to repeatedly find the smallest or largest element while values are being added or removed, a heap is one of the first data structures you should consider.
Here are the operations we built in this chapter, for a binary heap with n elements:
To make sure you've understood the concepts, try implementing insert, extractMin, and peek from scratch.
10 quizzes