Home / Patterns / Heaps

Heaps Pattern Hub

7 problems

Find Median from Data Stream

hard
TC: O(log N) · SC: O(N)

Maintain 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

medium
TC: O(N log k) · SC: O(k)

Maintain 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

easy
TC: O(N log k) · SC: O(k)

Maintain 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

easy
TC: O(N log N) · SC: O(N)

Simulate 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

hard
TC: O(N log k) · SC: O(1)

Either 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

medium
TC: O(T) · SC: O(1)

Most 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

medium
TC: O(N) · SC: O(N)

Bucket 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.