- 1
Heaps are used to maintain a maximum or minimum value in a dataset. Our examples use numbers since this is a straight-forward value, but heaps have many practical applications. Imagine you have a…

- 2
We can picture min-heaps as binary trees, where each node has

**at most**two children. As we add elements to the heap, they’re added from left to right until we’ve filled the entire level. At th… - 3
Sometimes you will add an element to the heap that violates the heap’s essential properties. We’re adding […] as a left child of […] , which violates the min-heap property that children m…

- 4
Maintaining a minimum value is no good if we can never retrieve it, so let’s explore how to remove the root node. In the diagram, you can see removing the top node itself would be messy: there wo…

- 1
We’re going to implement a min-heap in Python. Min-heaps efficiently keep track of the

**minimum value**in a dataset, even as we add and remove elements. Min-heaps are nearly identical to a max… - 2
Our […] class will store two pieces of information:

- A Python list of the elements within the heap.
- A count of the elements within the heap.

To make our lives easier, we’ll always keep on…

- 3
The min-heap is no good if all it ever contains is […] . Let’s build the functionality to add elements while maintaining the heap properties.

Our […] will abide by two principles:

- The e…

- 4
Great work so far! Our […] adds elements to the internal list, keeps a running count, and has the beginnings of […] . Before we dive into the logic for […] , let’s review how heaps track…

- 5
Now that we understand how to determine the relationship of elements with the internal list, we’re ready to finish […] . We need to make sure that every child is greater in value than their pa…

- 6
Min-heaps would be useless if we couldn’t retrieve the minimum value. We’ve gone through a lot of work to maintain that value because we’re going to need it!

Our goal is to

**efficiently remove**… - 7
We’ve retrieved the minimum element but left our […] in disarray. There’s no reason to get discouraged, we’ve handled this type of problem before, and we can get our […] back in shape!

We…

- 8
We mentioned […] is a lot like […] . We’ll track an offending element in the heap, and keep swapping it with another element until we’ve restored the heap properties. The wrinkle is […] …

- 9
We’ve got a handy helper to tell us which child element is smaller, so there’s nothing standing between us and a pristine heap.

As a reminder, our strategy will be very similar to […] , but we…

- 10
Nice work! You’ve implemented a min-heap in Python, and that’s no small feat (although it could efficiently track the smallest feat). To recap: […] tracks the minimum element as the element a…

## How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory