Heap
Keep a growing collection where the smallest (or largest) item is always instantly available, and adding or removing items stays cheap.
After this lesson you will be able to
- Explain the heap property and why a heap can be stored in a plain array.
- Trace insert (sift up) and extract-min (sift down) and explain why each is O(log n).
- Use Python's
heapqfor min-heaps, max-heaps (by negating) and heaps of tuples. - Solve “k-th largest”, “top k” and “merge k sorted lists” problems with a heap of bounded size.
- Recognise when you repeatedly need the current minimum or maximum while the data changes.
Before you start. Arrays (index arithmetic) and Trees (parent and child vocabulary). Sorting Basics shows what a heap replaces.