sagelearnai

Heap / Priority Queue

Signal: "k largest / smallest / closest / most frequent", "merge k sorted…", "always process the cheapest/earliest next", scheduling, or a running median over a stream.

Core idea: a binary heap keeps the minimum (or maximum) at the root, with O(log n) push/pop and O(1) peek. It's a complete binary tree stored in an array: the children of i are 2i+1 and 2i+2.

1 3 2 7 4 5 132745 array layout: parent(i) = (i−1)//2,children of i at 2i+1 and 2i+2 min-heap: every parent ≤ its children

Patterns

GoalHeapSize
k largest elementsmin-heap: pop the smallest when size > kk → O(n log k)
k smallest / closestmax-heap (negate values in Python)k
Merge k sorted listsmin-heap of the current headsk → O(N log k)
Running medianmax-heap (lower half) + min-heap (upper half)balanced
Greedy schedulingmax-heap by remaining count/prioritytasks
python
import heapq                       # Python's heapq is a MIN-heap
h = []
heapq.heappush(h, 5); heapq.heappush(h, 1)
heapq.heappop(h)                   # 1
heapq.heappush(h, -x)              # max-heap trick: store negatives
heapq.nlargest(3, nums)            # handy built-ins

JavaScript has no built-in heap, so in interviews either write a small one (below) or say you'd use a library. Solutions in this section include a compact MinHeap.

javascript
class MinHeap {
  constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
  get size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(x) { const a = this.a; a.push(x); let i = a.length - 1;
    while (i > 0) { const p = (i - 1) >> 1; if (this.cmp(a[i], a[p]) >= 0) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } }
  pop() { const a = this.a, top = a[0], last = a.pop();
    if (a.length) { a[0] = last; let i = 0;
      for (;;) { const l = 2 * i + 1, r = l + 1; let m = i;
        if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
        if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
        if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } }
    return top; }
}

Problems

  1. Kth Largest Element in a Stream (Easy): Persistent min-heap of size k
  2. Last Stone Weight (Easy): Max-heap, smash the two heaviest
  3. K Closest Points to Origin (Medium): Max-heap of size k by squared distance
  4. Kth Largest Element in an Array (Medium): Min-heap of size k (or Quickselect)
  5. Top K Frequent Words (Medium): Count, then order by (-freq, word); a size-k heap needs the inverted tie-break
  6. Task Scheduler (Medium): Most frequent task dictates the frame; or simulate with a max-heap
  7. Reorganize String (Medium): Impossible iff maxFreq > (n+1)/2; otherwise fill even indices first with the most frequent letter
  8. Find Median from Data Stream (Hard): Max-heap for the lower half, min-heap for the upper half
  9. Sort Characters By Frequency (Medium): Count, then bucket by frequency (or sort by count)
  10. Single-Threaded CPU (Medium): Sort by enqueue time; min-heap of available tasks keyed (processing, index); jump time when idle
  11. Maximum Subsequence Score (Medium): Sort by nums2 desc; each element in turn is the min; keep the k largest nums1 with a min-heap
  12. IPO (Hard): Sort by capital; unlock affordable projects into a max-heap of profit; take the best k times
  13. Smallest Range Covering Elements from K Lists (Hard): Keep one pointer per list in a min-heap; track the current max; advance the min
  14. Design Twitter (Medium): Per-user tweet lists with global timestamps; news feed = k-way merge of followees' recent tweets