Tracking extremes, medians, and K largest/smallest elements in dynamic streams
194 problems·15 Easy·105 Medium·74 Hard
Pattern Study Guide & Cheat Sheet· O(n log k) vs O(n log n) full sort · O(k) auxiliary memory
▼
Dynamically maintain the K extreme elements using a binary heap, turning an O(N log N) full sort into O(N log K) time.
Core Invariant: The Heap Inversion Principle: To maintain the top K LARGEST elements, use a MIN-heap of size K! The heap root holds the smallest of the top K; if a new element is larger than root, pop root and push new.
Recognize it (Keywords & Signals)
Find K-th largest or K-th smallest element in array or stream
Top K frequent elements or most frequent words
Merge K sorted linked lists / arrays
Find median from data stream (dual heap: max-heap + min-heap)
Task scheduler / meeting rooms
When NOT to use
K is very close to N (quickselect or full sort is faster and simpler), or random indexed lookups are needed.
How to solve (Step-by-step)
1.To find top K largest: maintain `min_heap = []` (in Python `heapq` is a min-heap by default).
2.Iterate through elements or frequency counts.
3.Push onto heap: `heapq.heappush(heap, item)`.
4.If `len(heap) > k`: pop smallest element: `heapq.heappop(heap)`.
5.Heap now holds the K largest elements; root `heap[0]` is the K-th largest.
Watch for (Interview Traps)
Using a max-heap for top K largest (requires pushing all N elements taking O(N log N) space and time)
Python's `heapq` is MIN-heap only; negate numbers `(-val)` to emulate max-heap behavior
Tuple comparison tie-breakers: if frequencies match, Python compares the next tuple element (ensure elements are comparable)
Top K Frequent Elements (Min-Heap of size K)
import heapq
from collections import Counter
def top_k_frequent(nums: list[int], k: int) -> list[int]:
freq_map = Counter(nums)
# Min-heap stores tuples: (frequency, number)
min_heap = []
for num, count in freq_map.items():
heapq.heappush(min_heap, (count, num))
# Keep heap size <= k so root is always the smallest among top k
if len(min_heap) > k:
heapq.heappop(min_heap)
return [num for count, num in min_heap]
Cost
O(n log k) vs O(n log n) full sort · O(k) auxiliary memory (Significant speedup when k << n (e.g. k=10, n=1,000,000).)
Canonical problems
#215 Kth Largest Element in an Array:Min-heap of size K yields answer at root heap[0]
#347 Top K Frequent Elements:Heap sorted by frequency maintains top K elements
#295 Find Median from Data Stream:Balance max-heap (lower half) and min-heap (upper half)
#23 Merge k Sorted Lists:Min-heap of size K holds head of each list for O(N log K) merge
Top K Elements & Priority Queues frequently asked questions
What is the Top K Elements & Priority Queues pattern in coding interviews?
Tracking extremes, medians, and K largest/smallest elements in dynamic streams It is categorized under Data Structures and features 194 curated interview problems across Easy (15), Medium (105), and Hard (74) difficulties.
Which tech companies frequently test Top K Elements & Priority Queues?
Companies frequently asking Top K Elements & Priority Queues questions include Google, Amazon, Meta, Microsoft, Bloomberg, Uber.
How do I master the Top K Elements & Priority Queues pattern?
Start by studying the algorithmic strategy and template code, then practice Easy and Medium problems before attempting Hard problems under timed conditions.