Heaps Pattern Hub
7 problemsFind Median from Data Stream
hardMaintain two balanced heaps: `lo` (max-heap of lower half) and `hi` (min-heap of upper half). Preserve two invariants on every `addNum`: (1) `max(lo) <= min(hi)`, and (2) `len(lo) >= len(hi)` differing by at most 1. Cleanest 3-step push: push into `lo`, pop `max(lo)` to `hi`, and if `len(hi) > len(lo)` pop `min(hi)` back to `lo`.
K Closest Points to Origin
mediumMaintain a bounded max-heap of size `k` keyed by squared Euclidean distance `x^2 + y^2` (skip `sqrt` to avoid floats). Any larger candidate evicts itself if `len > k` (or Quickselect for O(N) expected time).
Kth Largest Element in a Stream
easyMaintain a **min-heap** capped at size `k`: elements smaller than the k-th largest are evicted on `heappop`. The root `heap[0]` is always the k-th largest element.
Last Stone Weight
easySimulate greedy extraction of the two heaviest stones using a max-heap (`-val` in Python min-heap): while `len(h) > 1`, pop `y`, pop `x`, and if `y != x` push `y - x`.
Merge k Sorted Lists
hardEither push the head of each non-empty list into a size-k min-heap (`O(N log k)` time, `O(k)` space) OR pairwise divide-and-conquer merge halves (`O(N log k)` time, `O(1)` extra heap allocations).
Task Scheduler
mediumMost frequent task (`maxFreq` occurring `maxCount` times) dictates frame geometry: `(maxFreq - 1)` full chunks of length `(n + 1)`, plus a final partial frame of `maxCount` tasks. If non-max tasks fill all idle slots, total time simply equals `len(tasks)`: `max(len(tasks), (maxFreq - 1) * (n + 1) + maxCount)`.
Top K Frequent Elements
mediumBucket Sort on Frequency: count occurrences in a hash map, then place elements at index `buckets[freq]` (size `N + 1`). Scan buckets from N down to 1 to harvest top k in strictly linear O(N) time.