Iteration

Heap

Lesson

Sometimes you want to find the minimum in an Array that changes slowly. Here's an example:

It normally takes O(n)O(n) time to find the minimum element, but notice that there's actually a lot of redundant computation here - many of the same numbers show up in each minimum. A "Heap" data structure lets you take the minimum faster, by remembering the previous numbers you saw.

A Heap is a Tree where all the elements get bigger as you step down:

Finding the minimum element in a heap takes O(1) time, since it's just the root node of the heap.

Adding and removing elements takes O(log n) time, because adding and removing simply bubbles an element up or down and heaps are always balanced.

Suprisingly, you can create a Heap in O(n) time - this is faster than adding 1 element to the Heap at a time, which would take O(n log n) time. This is why creating a heap has a special name, called "Heapify".

Read Time Complexity O(1)O(1) to find minimum.

Insert/Delete Time Complexity O(logn)O(\log n)

Create Time Complexity O(n)O(n)

Example

Here's how you use a Heap to speed up the above example:

Other things to know

Heaps are stored as Arrays, and not as Trees. This is possible to do efficiently because they're always balanced, and elements are always added left-to-right. This allows them to be stored in the order of a BFS traversal. The above Heap is stored as [1, 5, 4, 6, 5, 8, 11, 10, 7, 8].

Heaps let you remove the root element, but typically not other elements. If you think you'll need to remove elements other than the min one, one common trick is to store a Set to remember those elements, and if you see them at the root of the heap, just pop them. The heap size effectively becomes n + |lazy|.

Implementation details

Most interview questions ask you to simply use Heaps, which doesn't require knowing how they work under the hood. Here's how they work for the curious.

Mark as Completed:
Submits:
test
Test your code to get an output here!