🧮Heap (Data Structure)
Also known as Heap, Min-Heap, Max-Heap, Priority Queue
A tree that keeps the smallest item on top, or the largest.
Think of it like
Think of it like a doctor's waiting room. The sickest person goes next.
Example
Jack's task runner keeps jobs in a heap by urgency. Whatever is most urgent comes out next, even if it arrived last.
Why it matters
Heaps pick the next job in task lists. Map apps use them to find short routes too.
Definition
Example code
python
>>> import heapq
>>> h = [5, 1, 8]
>>> heapq.heapify(h)
>>> heapq.heappop(h)
1Common mistake
Key takeaways
- 1Top item first. Smallest or largest.
- 2Partly sorted. Just enough for the top.
- 3A priority queue. Its most common use.