Category
heaps
3 articles
Two Heaps Pattern: Find the Median of a Data Stream Without Sorting
TLDR: Two Heaps partitions a stream into two sorted halves. A max-heap holds everything below the median; a min-heap holds everything above it. Keep the heaps size-balanced and you can read the median from either top in O(1) — no sorting needed, ever...
Top K Elements Pattern: Find the Best K Without Sorting Everything
TLDR: To find the top K largest elements, maintain a min-heap of size K. For every new element, push it onto the heap. If the heap exceeds K, evict the minimum. After processing all N elements, the heap holds exactly the K largest. O(N log K) time — ...
K-Way Merge Pattern: Merge K Sorted Sequences with a Min-Heap
TLDR: K-Way Merge uses a min-heap with exactly one entry per sorted input list. Each entry stores the current element's value plus the coordinates to find the next element in that list. Pop the minimum (global smallest), append it to output, push the...
