Heaps & Priority Queues in Python
Chapter 49: Heaps & Priority Queues
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
A heap built from scratch: sift up and sift down
A binary heap is a list read as a tree, where index i's children are 2i + 1 and 2i + 2, kept so that every parent is no bigger than its children; then the smallest is always at index 0, a new item sifts up from the end, and after the top is taken the last item sifts down from the top.
Building a heap in O(n), and heapsort
To heapify a list, sift down each parent, starting from the last parent and working back to the root, so that by the time a node is fixed, both subtrees below it are already heaps; then heapsort pops the smallest n times.
Top k and the k-th largest
To find the k largest values, push each value into a min-heap and pop whenever it holds more than k; the heap then holds the k largest, and its top is the k-th largest.
Merging k sorted lists; the running median with two heaps
To merge k sorted lists, keep one item per list (its current front) in a min-heap and repeatedly pop the smallest and push the next item from the same list; for the running median, keep the smaller half in a max-heap and the bigger half in a min-heap, balanced in size, so the median is at the tops.