Unit 6 of 8 · about 4 hours · derive, implement

Heaps and priority queues

Heaps buy priority operations in logarithmic time with plain array storage. The linear build and the two-heap median are the two derivations that recur everywhere else.

You'll be able to

  • Derive why bottom-up heap construction is linear while repeated insertion is .
  • Implement sift-up, sift-down, Floyd build, push, pop and replace with invariant tests, using heapq only as an oracle.
  • Implement the two-heap streaming median and defend its size and ordering invariants.

Covers

Heap order, bottom-up construction and mutable priorities
1

Read

In this order, only the parts listed

0 of 2 done

  1. Heaps and priority queuesDSA Handbook - search, trees and heaps

    What a heap actually is; The two primitives; The full operation table; Building a heap in linear time; Worked example: LC 295; Where readers go wrong

    Skim the LC 215 and LC 23 worked examples; kth-largest belongs to the quickselect unit and k-way merge is not assigned.

  2. Two-heap median archetypes: when one heap is not enoughDSA Handbook Patterns - two-heap median archetypes

    Streaming median (two-heap balance invariant); Variants side-by-side

    Skip sliding-window median and the sketch survey; only the append-only variant is implemented here.

2

Focus on

  • Most nodes are leaves with short subtrees: level holds about nodes at sift cost each, and the series times sum converges to . Repeated insertion instead pays , which is .
  • Floyd starts at n//2 - 1, the last internal node, and moves right to left so every sift-down sees valid child heaps. That order is the MAX-HEAPIFY precondition; building by sift-up throws the linear bound away.
  • Two-heap invariants: 0 <= len(lower) - len(upper) <= 1 with the extra element in lower, and max(lower) <= min(upper). Push-then-rotate maintains both with per insert and per query.
  • heapq is min-heap only and heapify runs in documented time. Max-heap idioms negate keys, and payloads need a tiebreak slot (the LC 23 tuple trick) so equal priorities never compare task objects.
Common mistakes · 3
  • Calling sift-down on a node whose children are not heaps yet. The child-heaps precondition is load-bearing; Floyd's right-to-left order is what establishes it.
  • Rebalancing the two heaps in the wrong order. Push to lower, move its top to upper, then rotate back only if upper outgrew lower; skipping the last step breaks the size invariant on even totals.
  • Averaging the two middle values with // instead of /. Floor division truncates the even-case median (1.5 becomes 1).
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement Floyd max-heap build plus push and pop. With random.seed(0) and random.sample(range(10**6), 2000), assert the result is a valid max-heap holding the same multiset, and count comparisons (at most ). Implement MedianFinder with the push-then-rotate rule: after add(1) and add(2) the median is 1.5; after add(3) it is 2.0. Differential-test both against heapq and brute-force medians on random streams.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Prove Floyd's build is .Answer

    Nodes at height number about and each costs at most sift steps. The total is at most times the sum of over all , and that series converges to 2, giving at most about sift steps and comparisons. Naive repeated insertion instead pays , which is by Stirling.

  2. 2.Why must the build loop start at n//2 - 1 and go down?Answer

    Indices [n//2, n) are leaves, which are trivially valid single-element heaps, so n//2 - 1 is the last internal node. Descending guarantees both children are already valid heaps when a node is sifted, which is the sift-down precondition.

  3. 3.State both two-heap invariants and compute the median for odd and even totals.Answer

    Size: lower holds at most one element more than upper, never fewer. Ordering: every lower key is at most every upper key. Odd total: the median is lower's root. Even total: the average of the two roots.

  4. 4.heapq has no max-heap. How do you store (priority, task) pairs, and what breaks on ties?Answer

    Push (-priority, index, task) with a tiebreak counter: negation flips the order and the counter keeps task objects uncompared. Without it, equal priorities fall through to comparing tasks, which raises TypeError for unordered types.

5

Practice

  • LeetCode 703: Kth Largest Element in a Stream

    Size-k min-heap with heapreplace; include k=1 and duplicate-heavy streams

    After submitting, read the AlgoMaster write-up for Kth Largest Element in a Stream (https://algomaster.io/learn/dsa/kth-largest-element-in-a-stream).

  • LeetCode 295: Find Median from Data Stream

    Two-heap MedianFinder; example sequence add(1), add(2), findMedian expects 1.5, then add(3), findMedian expects 2.0

    Attempt cold. After submitting, read the AlgoMaster write-up for Find Median from Data Stream (https://algomaster.io/learn/dsa/find-median-from-data-stream).

You're done when

Floyd build holds heap order with at most 2n comparisons on the 2000-element seed-0 input, the median matches brute force on random streams, and you can state both invariants plus the linear-build series without notes.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 8 more in the section
  • DSA Handbook - search, trees and heapsHandbook Academy · primary

    Study Part 2 Search and Sort, Part 5 Linked Lists, and Part 6 Trees and Heaps. Include canonical and answer-space binary search, comparison and linear-time sorts, quickselect, sentinels, cycles, heaps, BSTs, balanced-tree vocabulary, tries and segment trees.

  • DSA Handbook Patterns - two-heap median archetypesHandbook Academy · support

    Use Streaming median and Variants side-by-side for the two-heap invariants; skip sliding-window median and sketches.

Also in this section

  • AlgoMaster DSA - ordered structures sliceAlgoMaster · required

    Attempt Koko Eating Bananas, Validate Binary Search Tree and Find Median from Data Stream cold. Use Merge Intervals only if interval modeling remains weak, and include duplicate-heavy and skewed inputs.

  • Algorithmica - search and sorting performanceSergey Slotin · support

    Use the binary-search, sorting, branch prediction and cache chapters to explain why two algorithms with the same asymptotic bound cross over on real workloads.

  • AlgorithmsJeff Erickson · reference

    Use Chapter 1 (mergesort, quicksort, recursion trees and linear-time selection) when deriving merge, partition and selection algorithms, and lecture note 12 Lower Bounds for the comparison-sorting decision-tree argument. This is the proof reference when the handbook explanation is too brief.

  • NeetCode - unseen ordered problemsNeetCode · optional

    Use one unseen tree problem and one heap or interval problem as the final transfer check, with solution material closed until submission.

  • DSA Handbook Patterns - quicksort vs mergesort vs heapsortHandbook Academy · support

    Use The decision, Algorithms compared and Side-by-side to pick a comparison sort from the binding constraint; problem details stay with their units.

  • DSA Handbook Patterns - quickselect vs heap for top-KHandbook Academy · support

    Use The decision through Side-by-side for the streaming, sorted-output and mutation routing; problem details stay with their units.

  • DSA Handbook Patterns - merge intervals archetypesHandbook Academy · support

    Use The decision, Variants and the LC 56 and LC 57 signature problems for merge and insert implementation, and the Meeting Rooms II archetype for the min-heap form.

  • DSA Handbook Patterns - sweep line archetypesHandbook Academy · support

    Use The decision and the 1D event sweep variant for +1/-1 concurrency counting with explicit tie-breaks; skyline and rectangle area are recognition only.