- 1Heaps 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…
- 2We 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… - 3Sometimes you will add an element to the heap that violates the heap’s essential properties. We’re adding 3 as a left child of 11, which violates the min-heap property that children must be larg…
- 4Maintaining 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…

- 1We’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… - 2Our MinHeap 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… - 3The min-heap is no good if all it ever contains is None. Let’s build the functionality to add elements while maintaining the heap properties. Our MinHeap will abide by two principles: * The elem…
- 4Great work so far! Our MinHeap adds elements to the internal list, keeps a running count, and has the beginnings of .heapify_up(). Before we dive into the logic for .heapify_up(), let’s review how…
- 5Now that we understand how to determine the relationship of elements with the internal list, we’re ready to finish .heapify_up(). We need to make sure that every child is greater in value than th…
- 6Min-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**… - 7We’ve retrieved the minimum element but left our MinHeap in disarray. There’s no reason to get discouraged, we’ve handled this type of problem before, and we can get our MinHeap back in shape! We…
- 8We mentioned .heapify_down() is a lot like .heapify_up(). We’ll track an offending element in the heap, and keep swapping it with another element until we’ve restored the heap properties. The wrin…
- 9We’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 .heapify_up(), …
- 10Nice 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: MinHeap 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