Priority Queue Patterns
A priority queue (PQ) is an abstract data type backed by a heap: you push items in any order, but always pop the highest-priority item first. Think of a hospital triage system — patients arrive in random order but the most critical case is always treated next, regardless of arrival time.
The key insight for interview problems: you almost never need the entire heap. You need a heap of size k, where k is some small constraint in the problem. This keeps space at \(O(k)\) and operations at \(O(\log k)\).
Pattern 1: K-th Largest Element
Maintain a min-heap of size k. For each element: push it onto the heap, then if size exceeds k, pop the minimum. When done, the root (minimum of the heap) is the k-th largest overall.
Why a min-heap? You want to evict the smallest among the current top-k candidates. The heap root gives you that cheaply.
← → arrow keys to step · click elements to interact
Priority Queue Patterns
Pattern 2: Merge K Sorted Lists
Given k sorted linked lists (or arrays), merge them into one sorted list. Push the head of each list into a min-heap with the list index. Repeatedly pop the minimum, append to result, and push the next element from the same list.
Pattern 3: Top-K Frequent Elements
Build a frequency map (\(O(n)\)), then use a min-heap of size k keyed by frequency. Same eviction trick as K-th largest: if heap size exceeds k, pop the least frequent. The k remaining elements are the top-k most frequent.
Bucket sort alternative: Create an array of buckets indexed 0 to n (frequency as index). Fill each bucket with elements of that frequency. Read from the back until you have k elements. \(O(n)\) time and space.