

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Priority Queues
incomplete
2: Priority Queue Code
incomplete
3: Heaps
incomplete
4: Why Use Heaps?
incomplete
5: Pop
incomplete
6: Priority Queue With a Heap
incomplete
This lesson's interactive features are locked, please to keep using them
As you probably noticed, the API of our new MinHeap class is very similar to the API of our PriorityQueue class. In fact, a heap is an ideal structure for a priority queue.
Remember that our original naïve implementation of a priority queue was just a list. It had the following Big O complexities:
push: O(1)peek: O(n)pop: O(n)Once we upgraded to a min heap, we got the following time complexities:
push: O(log(n))peek: O(1)pop: O(log(n))The difference between O(log(n)) and O(n) is huge!
Imagine we need to pop a value from a priority queue with 1 million elements:
O(n) implementation, we need to look at all 1 million elements to find the one with the lowest priority.O(log(n)) implementation, we access the lowest-priority element immediately at the root, then we only need ~20 operations to maintain the heap structure. That's about 50,000x faster!It may look like we're sacrificing time complexity on push, but at scale, the difference between O(1) and O(log(n)) is much smaller than the difference between O(log(n)) and O(n). This is important to keep in mind when choosing data structures and algorithms.