Heaps & Priority Queues
Heaps are complete binary trees satisfying the heap property.
Complete means each level is full until the last one filled left-wise.
In a Min/Max-heap, each parent node's value is respectively less/greater than or equal to its
children's. Commonly implemented using arrays along operations:
- insert, adding element and maintaining heap property
- extract max/min, removing root and re-heapifying
- heapify, building a heap from an array
Heaps efficiently implement Priority Queues, where elements are retrieved
based on priority. Applications include finding the top K elements in
a collection, event simulation, and in algorithms like Dijkstra's shortest path.
Min-Heap via Python's heapq
In Python, a Heap of the min-heap variant is directly available
via the stdlib package heapq.
It exposes a set of functions to apply onto a regular list.
from heapq import *
heapify(h :=
[12, 48, 6, 3, 1]) # h = [1, 3, 6, 12, 48]
heappush(h, 10) # h = [1, 3, 6, 12, 48, 10]
heappush(h, 5) # h = [1, 3, 5, 12, 48, 10, 6]
heappop(h) # h = [3, 6, 5, 12, 48, 10]
heappop(h) # h = [5, 6, 10, 12, 48]
heappop(h) # h = [6, 12, 10, 48]
heappop(h) # h = [10, 12, 48]