Heaps / Priority Queues
IntermediateData Structures
Heaps efficiently maintain the max or min element. Python's heapq is a min-heap. The top-K pattern and merge-K-sorted-lists are classic Google questions.
AVG TIME
O(log n)
SPACE
O(n)
BEST
O(1)
WORST
O(log n)
Key Concepts
- 1Python heapq is min-heap; negate values for max-heap behavior
- 2Top-K elements: maintain heap of size K, O(n log k)
- 3heapq.heapify() builds heap from list in O(n)
- 4heapq.nlargest/nsmallest for one-off queries
- 5Merge K sorted lists: push (val, list_idx, element_idx) tuples
In Python
Math You Need For This
A sorting funnel. You pour items in the top and the smallest always floats to the tip. The funnel has log(n) levels, so settling an item into place takes log(n) swaps.
Required concepts
Key math ideas
1 / 2
Interactive 3D Visualization
Python Implementation
Now try it yourself
1 challenge with test cases and AI feedback
Practice Now
Complexity Analysis
Heaps / Priority Queues
Next: Tries