AlgoMaster Logo

Introduction to Heaps

High Priority19 min readUpdated November 8, 2026
Listen to this chapter
Unlock Audio

Premium Video

This video is available to premium subscribers only

Unlock Full Access

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.

Why Heaps?

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:

  • Priority queues, which hand out the most important item first.
  • Task scheduling, where the next job to run is the one with the earliest deadline or the highest priority.
  • Shortest-path algorithms like Dijkstra's algorithm.
  • Coding interview problems where we need to efficiently keep track of the smallest or largest elements.

What Is a Heap?

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:

25974

Let's look at both rules.

1. Complete Binary Tree

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:

  • It keeps the height of the tree logarithmic. A complete binary tree with n nodes has a height of about log₂(n), so any path from the root to a leaf is short.
  • It allows us to store the entire heap in a simple array without needing pointers. We'll see how in a moment.

2. Heap Property

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.

Min-Heap vs Max-Heap

In a min-heap, every parent is less than or equal to its children.

25974

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.

97245

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.

Storing a Heap in an Array

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:

  • The root is stored at index 0.
  • Its two children are stored at indices 1 and 2.
  • The next level occupies indices 3, 4, 5, and 6, and so on.

Here is our min-heap with the array index shown on each node:

25974

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:

  • Its left child is at index 2 * i + 1.
  • Its right child is at index 2 * i + 2.
  • Its parent is at index (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.

Insert and Sift Up

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:

  1. We compare the new element with its parent. If it's smaller, we swap the two.
  2. We then compare it with its new parent and repeat the process.
  3. We continue moving the element upward until it's no longer smaller than its parent or it reaches the root.

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.

Walkthrough

Let's walk through an example. Suppose we have this min-heap, [2, 5, 4, 9, 7], and want to insert the value 1.

25974

We start by adding 1 at the end of the array, at index 5. The array is now [2, 5, 4, 9, 7, 1].

259741

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].

259714

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].

159724

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.

Code

Now, let's see how to implement this in code.

  1. First, we add the new value to the end of the array and set i to its index.
  2. Then, as long as i is greater than zero, we calculate the parent index as (i - 1) / 2 using integer division.
  3. If the current element is greater than or equal to its parent, the min-heap property is already satisfied, so we stop.
  4. Otherwise, we swap the element with its parent, update 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.

Extract Min and Sift Down

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:

  1. First, we save the root value so we can return it later.
  2. Then, we take the last element in the array, move it to the root, and remove the last slot.

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:

  1. We compare the current element with its children.
  2. If it's larger than either child, we swap it with the smaller of the two.
  3. Then, from its new position, we repeat the same process.

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.

Walkthrough

Let's walk through another example, using the heap we got from the insert walkthrough: [1, 5, 2, 9, 7, 4].

159724

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].

45972

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].

25974

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.

Code

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:

  1. We start by assuming the current element is the smallest.
  2. We then calculate the indices of its left and right children.
  3. If a child exists and has a smaller value, we update smallest to point to that child.
  4. After checking both children, if smallest is still the current index, the heap property is satisfied, so we stop.
  5. Otherwise, we swap the current element with the smaller child, update the index, and repeat the process.

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.

Peek

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.

Building a Heap from an Array

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:

  1. We know that all leaf nodes already satisfy the heap property because they have no children.
  2. So we can skip them and start with the last non-leaf node, which is at index n / 2 - 1, using integer division.
  3. From there, we move backward toward the root, calling 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.

Walkthrough

Let's walk through an example using this unsorted array: [9, 5, 4, 2, 7, 1].

952741

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].

952714

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].

925714

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].

125794

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].

125749

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.

Code

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).

Why Building a Heap Takes O(n) Time

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:

  • Roughly half of the nodes are leaves, which already satisfy the heap property, so they require no work.
  • About a quarter of the nodes are just one level above the leaves, so they can move down by at most one level.
  • About an eighth are two levels above the leaves, so they can move down by at most two levels.
  • And so on.

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:

Scroll

Level above the leaves

Nodes

Max moves per node

Max work

0 (leaves)

8

0

0

1

4

1

4

2

2

2

4

3 (root)

1

3

3

Total

15

 

11

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.

Heaps and Priority Queues

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.

When to Use a Heap

Now that we understand how heaps work, let's look at when we should use them. There are a few common patterns worth recognizing.

Top K or Bottom K

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].

Merging K Sorted Lists

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.

Scheduling and Simulations

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.

Shortest Paths

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.

The Rule of Thumb

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.

Summary

Here are the operations we built in this chapter, for a binary heap with n elements:

Scroll

Operation

Time

What it does

peek

O(1)

Read the root at index 0

insert

O(log n)

Add at the end, then sift up

extractMin

O(log n)

Move the last element to the root, then sift down

buildHeap

O(n)

Sift down every non-leaf node, from the last one back to the root

To make sure you've understood the concepts, try implementing insert, extractMin, and peek from scratch.

Quiz

Introduction to Heaps Quiz

10 quizzes