^Topic
Heap / Priority Queue Problems
Heap and priority-queue problems — top-K elements, median maintenance, and event scheduling.
Medium · 1
Hard · 2
Heaps (priority queues) solve a family of problems where you repeatedly need the smallest or largest element from a changing set. They give you O(log n) insert and O(log n) extract-min/max — perfect for top-K, K-way merge, scheduling, and streaming median.
Three patterns dominate. Top-K keeps a heap of size K and slides through the input — O(n log K) instead of O(n log n). Two-heap median uses a max-heap for the lower half and a min-heap for the upper half, balancing them so the medians are always at the roots. K-way merge seeds a min-heap with one element from each of K sorted sources and pulls the global minimum repeatedly — the basis for merge-K-sorted-lists.
The Ratta heap track covers Top K Frequent Elements, Find Median from Data Stream, Last Stone Weight, K Closest Points to Origin, and Task Scheduler. Each problem includes the heap configuration (min vs. max), the invariant that keeps the answer at the root, and complete implementations in C++ (priority_queue), Java (PriorityQueue), Python (heapq), and Go (container/heap).