Min Heap - Taking Out the Most Urgent Item First
Heap = a tree structure that keeps the rule "a parent is always smaller than its children (min heap)." It is represented as an array: the children of the parent at index i are at 2i+1 and 2i+2.
(1) ← root = always the minimum
/ \
(3) (2)
/ \
(7) (5)- peek: see the minimum → just look at the root → O(1)
- push: add at the end, then move it up while comparing with its parent (
_heapify_up) → O(log n) - pop: take out the root, move the last element to the root, then move it down while comparing with its children (
_heapify_down) → O(log n)
Why Is a Heap a Good Fit for TTL Management?
TTL stores (expire_at, key) and has to keep asking which one expires first.
- The one with the smallest expiration time = the minimum → it is always at the root of the heap!
- This is far more efficient than sorting or scanning everything each time.
Summary
| Concept | Plain-language summary |
|---|---|
| Min heap | A pyramid where the smallest/most urgent item is always on top |
Source: Codyssey-B1/B5-1
