Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Helper data structures and core patterns

Heap

A heap is a collection that always gives back the smallest element first (min heap), or the greatest one (max heap). You should use a heap whenever you repeatedly need the smallest or the greatest element of a collection that keeps changing.

A heap is the common way to implement a priority queue, so the two names are often used for the same thing.

2
4
5
8
push adds a value, pop takes the smallest

Time complexity

operationtime
read the smallest elementO(1)O(1)
add an elementO(log⁡n)O(\log n)
remove the smallest elementO(log⁡n)O(\log n)

Implementation

We build a min heap, where the smallest element is on top. A max heap is the same with every comparison reversed.

Array layout

A heap is a binary tree stored in an array. Index 0 is the root, and the children of index ii are at 2i+12i + 1 and 2i+22i + 2. Every parent is less than or equal to its children, so the smallest element is at index 0.

1
3
7
6
2
5
4
1
3
2
7
6
5
4
0123456
children of index i are at 2i + 1 and 2i + 2

Push the element

A new element goes to the end of the array. Then we move the element up, swapping it with its parent until the parent is smaller.

This takes O(log⁡n)O(\log n) at most.

3
5
7
6
8
3
5
8
7
6
012345
append 1
1 / 4

Pop the element

We swap the root with the last element and remove it from the end. Then we move the new root down, swapping it with its smaller child until both children are greater.

This takes O(log⁡n)O(\log n) at most.

1
3
7
6
5
8
1
3
5
7
6
8
012345
swap root 1 with last 8
1 / 5

Build it

Implement push, pop and peek in the class below. The index helpers and the code that uses the heap are already written.

Build a heap
Python
class MinHeap:
def __init__(self) -> None:
self.elements = []
def push(self, value: int) -> None:
# Add value to the heap
pass
def pop(self) -> int:
# Remove and return the smallest element
return None
def peek(self) -> int:
# Return the smallest element without removing it
return None
def _parent(self, i: int) -> int:
return (i - 1) // 2
def _left(self, i: int) -> int:
return 2 * i + 1
def _right(self, i: int) -> int:
return 2 * i + 2
heap = MinHeap()
for value in [5, 3, 8, 1, 4]:
heap.push(value)
print(heap.peek())
print(*[heap.pop() for _ in range(5)])
Was this lesson helpful?