Data Structures & Algorithms practice
Data Structures & Algorithms ยท Hierarchical Structures

Heaps & Priority Queues: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1The Heap PropertyEasyMust Do

A min-heap is a binary tree with two properties. It is complete: every level is full except perhaps the last, which fills from the left, so a level-order list of it has no gap before its last item (DSA Topic 13's complete trees). And it is ordered: every item is at least as large as its parent (child >= parent, tested with child < parent as the failure), so the smallest item sits at the root. The two children of a node are not ordered with each other, unlike a search tree's (DSA Topic 14). A tree is given as a level-order list, such as [1, 3, 2, None, 4], where None marks a missing child; TreeNode and from_level (which builds the tree from such a list and returns its root) are written out in the answer, as DSA Topic 13 built them.

  1. Write is_heap_tree(root): True when no node is smaller than its parent, checked node by node with a stack (no recursion).
  2. Paste is_complete(root) as DSA Topic 13 wrote it: True when the tree is complete, found by a level-order walk with a deque that keeps None children in the queue, so that once a None has been taken out no real node may follow.
  3. Print the verdicts for [1, 3, 2, 7, 4, 5] (a heap), [1, 3, 2, 0] (0 sits under 3) and [1, 3, None, 4] (not complete).
  4. Count the heaps among all orders of 1..k for k = 0..7 (by itertools.permutations) and assert that the root is the minimum in every one of them.
Q2The Array LayoutEasyMust Do

A complete binary tree needs no references. Write its items in level-order (level by level, each level left to right: DSA Topic 13 serialised trees this way) and the list has no gap before its last item, so slot i of the list holds exactly one node and the list is the tree. A heap is stored this way. Level d (the root is level 0) starts at index 2^d - 1 and holds up to 2^d items; only the last level may be short.

  1. Write levels(a), which cuts a list into the levels of its tree: [a[0]], then [a[1], a[2]], then [a[3], ..., a[6]], and so on. Print levels([1, 3, 2, 7, 4, 5]).
  2. Assert for every length n <= 100 that level d starts at index 2^d - 1, that every level but the last is full, and that there are n.bit_length() levels.
  3. Build three beds of test lists, written out in the answer: PERMS, every order of 0..k-1 for k = 0..7 (5,914 lists); DUPS, every list of length 0 to 7 over the values 0, 1, 2 (3,280 lists); and BED = PERMS + DUPS (9,194 lists).
  4. Round trip: from_level(a) builds the tree of a list (TreeNode and from_level are written out in the answer: from a level-order list with None gaps, from_level returns the root). A level-order walk of that tree with a deque must give back exactly a, with no None in it, for every list of BED.
Q3Parent And Child Index ArithmeticEasyMust Do

A heap lives in a 0-based list in level-order (level by level, left to right; the root is slot 0, level d starts at index 2^d - 1 and holds up to 2^d items). The tree is complete, so where a node's children and parent sit is fixed by arithmetic on its index. Derive it from the level starts: the j-th item of level d (counting from 0) sits at 2^d - 1 + j, and its two children are items 2j and 2j + 1 of level d + 1.

  1. Show the derivation as an assertion for every level d < 12 and every j < 2^d: the left child's index is 2^(d+1) - 1 + 2j, which equals 2i + 1 for i = 2^d - 1 + j.
  2. Write parent(i), left(i) and right(i) with their contracts: parent needs i >= 1 and gives (i - 1) // 2; the child formulas give 2i + 1 and 2i + 2, which may lie past the end of the list, so every caller tests < len(a) first.
  3. Assert parent(left(i)) == parent(right(i)) == i for every i < 10^4.
  4. Check the formulas against a real tree: from_level (written out in the answer: it builds the tree of a level-order list with None gaps and returns the root) hangs nodes under each slot. On every list of BED (every order of 0..k-1 and every list over 0, 1, 2, each of length 0 to 7: 9,194 lists, built in the answer), walk the tree with a deque beside the slot numbers and assert that the children it holds are exactly the items at left(i) and right(i) when those are < len(a), and None otherwise.
  5. Print i, parent(i), left(i) and right(i) for i = 0..6.
Q4Checking The Heap PropertyEasy

In a min-heap kept in a 0-based list (children of slot i at 2i + 1 and 2i + 2, parent at (i - 1) // 2) no item is smaller than its parent. Checking each item against its parent alone is enough, unlike a search tree, where checking only each node against its two children missed a key buried deeper (DSA Topic 14's tempting local check).

  1. Write is_heap(a): each item against its parent only, O(n).
  2. Write the brute-force check first_bad_pair(a): compare each item with every ancestor and return (ancestor index, index) for the first item that is smaller than one, or None; and heap_ok(a) on top of it. Cost O(n log n).
  3. Argue in three printed lines why the parent check is enough: <= chains along every path from the root.
  4. Confirm that is_heap and heap_ok agree on all 9,194 lists of BED (every order of 0..k-1 and every list over 0, 1, 2, each of length 0 to 7) and count the heaps.
  5. Broken variant is_heap_left_only, which checks only left children (odd slots): scan BED from the shortest list, orders before lists with repeats, for the first list it accepts but is_heap rejects, and show it beside the truth. Count how many lists of BED it gets wrong.
  6. Print first_bad_pair for a few near misses.
Q5One-Based IndexingEasy

Leave slot 0 of the list empty and the index arithmetic gets simpler: the children of slot i are 2i and 2i + 1, and the parent is i // 2. Many textbooks and C programs do this; Python's heapq is 0-based. A heap in this layout has its root at slot 1, so its items start at index 1.

  1. Assert that the two layouts agree for every i < 10^4: the 0-based slot i0 is the 1-based slot i0 + 1, so the 1-based parent and children of i0 + 1 are the 0-based ones plus 1.
  2. Write is_heap_1(a) for a list whose slot 0 is unused, and is_heap(a) for the 0-based list. Check is_heap_1([None] + a) == is_heap(a) on every list of BED (every order of 0..k-1 and every list over 0, 1, 2, each of length 0 to 7).
  3. The path from the root to slot i (1-based) spells i in binary after its leading 1, with 0 for left and 1 for right. Print the paths for i = 1..15 and assert the rule for every i < 2^12 by walking from slot 1.
Q6Peek And What The Top Tells YouEasy

peek reads a[0] of a min-heap (a 0-based list in which no item is smaller than its parent) and leaves the heap alone: O(1). On an empty heap it raises IndexError. The top is the minimum, but the heap does not tell you much more. The second smallest item is one of the root's two children, so it is the smaller of a[1] and a[2], not a[1].

  1. Write peek(a) with the empty-heap contract and show the error once.
  2. Take the heaps of BED (every order of 0..k-1 and every list over 0, 1, 2, each of length 0 to 7; a heap is a list in which no item is smaller than its parent) and assert peek(a) == min(a) on every non-empty one.
  3. Assert min(a[1:3]) == sorted(a)[1] on every heap with two or more items, and print how many there were.
  4. Broken variant second_b6, which returns a[1]: scan the heaps of BED from the shortest for the first one it gets wrong and show it beside the truth. Argue in two printed lines why the second smallest cannot be deeper than the root's children.
Q7Sift Up And PushEasyMust Do

A min-heap here is a Python list a read as a complete binary tree in level-order (the children of slot i are 2i + 1 and 2i + 2, its parent is (i - 1) // 2) in which no item is smaller than its parent, so a[0] is the smallest. Items are compared with < only. Push appends x in the next free slot, which keeps the tree complete, and then sifts it up: while it is smaller than its parent, swap the two. Only the path from the new slot to the root changes, and each swap repairs the one edge that was broken: the parent that moves down was already no larger than its other child, so it still obeys the rule there.

  1. Print the four-line argument that sift-up restores the heap rule.
  2. Write sift_up(a, i) and a class MinHeap with __init__, __len__, peek (IndexError when empty), push and _sift_up. Pop comes next, so leave it out. These helpers are written out in the answer: levels(a) cuts a list into the levels of its tree, is_heap(a) is True when no item is smaller than its parent, and heap_ok(a) is True when no item is smaller than any of its ancestors.
  3. Trace pushes of 5, 3, 8, 1, printing levels after each push.
  4. Check on every list of BED (every order of 0..k-1 and every list over 0, 1, 2, each of length 0 to 7: 9,194 lists): pushing the list's items one at a time keeps is_heap and heap_ok True after every push and holds the same items (equal when sorted). Also assert that no push makes more than floor(log2 n) swaps, with n the heap size after the push, using a counted copy of the climb that gives the same list.
  5. Broken variant push_b7, which loops while i > 1, so slot 1 is never compared with the root: scan BED from the shortest list for the first one it builds into a non-heap, and show it beside the right result.
Q8Push Costs: Best, Average, WorstMedium

A push into a min-heap (a Python list read as a complete binary tree in which no item is smaller than its parent) appends the item and swaps it up while it is smaller than its parent. How many comparisons that takes depends on where the new item belongs. Wrap values in a Key class whose < adds 1 to a counter, and count; never time the counted code.

  1. Write sift_up(a, i), push(a, x) and Key (every < between two keys adds 1 to Key.compares).
  2. A sorted list is already a heap. Take a heap of 10^5 keys that way and push one new maximum (the item that belongs at the bottom) and, on a fresh copy, one new minimum. Print both counts and assert that the maximum costs 1 comparison and the minimum costs floor(log2 n) for n the size after the push (n.bit_length() - 1).
  3. Build heaps by n pushes, one at a time from an empty list, for n = 10^3, 10^4, 10^5 and three input orders: a seeded random order of 0..n-1, ascending and descending. Print comparisons per push.
  4. Assert what the counts show: ascending costs n - 1 comparisons in all; descending costs exactly the sum of floor(log2(i + 1)) over i = 0..n-1 (every push climbs to the root); random order stays between 2.0 and 2.6 per push at every size. State the result from the printed numbers: a push is O(log n) worst case, and on random input it is close to constant per push on average (measured, not proved).
Q9Sift Down And PopEasyMust Do

A min-heap here is a Python list a read as a complete binary tree in level-order (the children of slot i are 2i + 1 and 2i + 2, its parent is (i - 1) // 2) in which no item is smaller than its parent, so a[0] is the smallest. Items are compared with < only. Pop saves a[0], moves the last item into slot 0 (the tree stays complete), and sifts it down: while one of its children is smaller, swap it with the smaller child. It must be the smaller child: the other child then stays below a parent no larger than itself. IndexError on an empty heap.

  1. Write sift_down(a, i, n), which sifts a[i] down inside a[0:n] (slots from n on are ignored), and complete MinHeap with pop and _sift_down. These helpers are written out in the answer: sift_up(a, i) swaps a[i] up while it is smaller than its parent; MinHeap has __init__, __len__, peek and push (append, then sift up); levels(a) cuts a list into the levels of its tree; is_heap(a) is True when no item is smaller than its parent; Key wraps a value so that each < adds 1 to Key.compares.
  2. Write random_list(n, rng, span), which returns exactly n ints drawn from range(span) with a seeded random.Random, and raises ValueError when n < 0 or when span < 1 and n > 0 (show the error once). Write the brute-force queue ListPQ: an unsorted list whose push appends and whose pop scans for the smallest item and removes the earliest of equal ones (IndexError when empty).
  3. Trace the heap built by pushing 5, 3, 8, 1, 9, 2, then pop everything, printing levels after each pop.
  4. Check: on every list of BED (every order of 0..k-1 and every list over 0, 1, 2, each of length 0 to 7: 9,194 lists), pushing the items and popping to empty gives sorted. Assert that a pop costs at most 2 * floor(log2 m) comparisons, m the heap size after the pop, on a heap of 1,023 Keys.
  5. Fuzz: 300 seeded scripts of mixed pushes and pops (values from 0..9) run against ListPQ, with is_heap checked after every step. Count the empty pops, the pops from a one-item heap, and the scripts with sorted, reverse-sorted and all-equal input; assert each was hit, and treat any Exception as a failure.
  6. Broken variant pop_b9, which overwrites the root with the last item before saving the root: scan the heaps of BED from the shortest for the first one where it returns the wrong item, and show it beside the truth.
Q10Pop Edge CasesEasy

Pop on a min-heap (a Python list read as a complete binary tree in which no item is smaller than its parent) moves the last item into the root and sifts it down. That step has edge cases. An empty heap has nothing to pop: IndexError with a message. A single item is the root and the last item at once: pop returns it and leaves [], and the move-last-to-root step must be skipped. Two items, and items that are all equal, need no special code but are worth running.

  1. Show each case with the heap written earlier in this topic (its MinHeap with push, pop and sift_down is written out in the answer): the empty pop and its message, a single item, two items, and five equal items.
  2. Broken variant pop_b10a, which saves a[0] and then writes a[0] = a.pop(): scan the heaps of BED (every order of 0..k-1 and every list over 0, 1, 2, each of length 0 to 7) from the shortest non-empty one for the first it breaks, and say why (the list is already empty once pop() has run).
  3. Broken variant pop_b10b, which returns a[0] without removing anything: scan for the first heap where the length does not shrink, and show the next pop returning the same item again.
  4. Then pop the real heap to empty on every list of BED, plus one more pop on each, and count the IndexErrors: one per list.
Q11Why The Smaller ChildEasy

A min-heap is a list a in which every item is at least as large as its parent. Slot i has its parent at (i - 1) // 2 and its children at 2 * i + 1 and 2 * i + 2, so [1, 5, 2] is a heap. A pop takes the smallest item from slot 0, moves the last item into slot 0 and sifts it down: sift_down(a, i, n) swaps a[i] with one of its children while that child is smaller, working inside the first n slots. The item has two children, so a rule must say which one to swap with. This question shows why the answer is "the smaller one".

  1. Sift slot 0 of [5, 1, 2] with the wrong rule (swap with the larger child) and print the result and the brute-force first_bad_pair (the first item that is smaller than one of its ancestors). Then sift with the right rule and print the result.
  2. A student's bug (B11 in the code) always swaps with the left child and never looks at the right one. Pop every item from every heap among the lists written out in the answer (all orders of 0..k-1 for k = 0 to 7, and all lists over 0, 1, 2 of length 0 to 7, so 9,194 lists, 540 of them heaps). Find the smallest heap whose pop order is not sorted, found by a plain scan in order of length, and print it beside the sorted truth.
  3. Count on how many of the 540 heaps the left-only pops come out unsorted, and assert the smaller-child rule comes out sorted on all of them.
Q12Heapify Bottom-UpMediumMust Do

A min-heap is a Python list a in which no item is smaller than its parent: the parent of slot i is (i - 1) // 2, and the children are 2 * i + 1 and 2 * i + 2, so a[0] is the smallest item. sift_down(a, i, n) moves a[i] down inside the first n slots, swapping it with its smaller child while that child is smaller. Given any list, heapify(a) must turn it into a min-heap in place and return None (as list.sort() does). The method: sift down every slot that has a child, from the last parent (slot n // 2 - 1) back to the root (slot 0). It runs backwards because when slot i is sifted, both subtrees below it are already heaps, so one sift_down makes the subtree at i a heap too; that is the loop invariant, and slot 0 finishes the whole list. Leaves (slots n // 2 and up) are one-item heaps and need nothing. The helpers sift_down, sift_up, levels (the list cut into tree levels), is_heap, a small MinHeap class with a list a and a push method, heap_of(items) (a new MinHeap built with heapify, not by pushes), random_list and the lists BED (every order of 0..k-1 for k = 0 to 7 plus every list over 0, 1, 2 of length 0 to 7) are written out in the answer.

  1. Write heapify and trace it on [9, 4, 7, 1, 8, 2, 6, 3, 5], printing levels after each sift.
  2. Check is_heap, the same items (compared sorted) and a None return on every list in BED and on 300 seeded random lists of 0 to 300 items, and check heap_of the same way.
  3. A student runs the loop forwards, from the root down (B12 in the code). Find the smallest list it fails on (a plain scan of BED in order of length) and print it beside the truth.
  4. Count comparisons and swaps (one < is a comparison, one exchange of two slots is a swap) for heapify against pushing the items one at a time, on random, ascending and descending lists of 1,000 and 10,000 items. State the cost: heapify is O(n) time and O(1) extra space, because a slot that is h levels above the bottom sifts at most h levels and most slots are near the bottom.
Q13Why Heapify Is O(n)MediumMust Do

heapify(a) turns a list into a min-heap (no item smaller than its parent) in place, by calling sift_down(a, i, n) on every slot i that has a child, from slot n // 2 - 1 down to slot 0. sift_down swaps an item with its smaller child while that child is smaller, working inside the first n slots. The height of slot i in a heap of n items is the number of levels below it: follow left children (2 * i + 1) until the index reaches n, and count the steps. A leaf has height 0. A sift from a slot of height h can move that item down at most h levels, so this question proves the total cost is linear. A swap is one exchange of two slots and a comparison is one <; popcount(n) is the number of 1 bits in the binary form of n. The helpers heapify, sift_down, sift_up, a small MinHeap class (a list a with a push method), best_of (the smallest time of 3 runs), random_list and the list PERMS (every order of 0..k-1 for k = 0 to 7, part of the larger test list BED) are written out in the answer.

  1. Count the heights from the layout: print how many slots of a heap of 15 and of 1,000 have each height (half are leaves, a quarter have height 1, an eighth have height 2, ...). Assert that the sum of all heights equals n - popcount(n) for every n below 3,000.
  2. So heapify makes at most n - popcount(n) swaps and at most twice that many comparisons. Assert both on every list of PERMS and print the worst swaps for each k beside the bound.
  3. Do the same on descending lists of 1,000, 10,000 and 100,000 items, and print the cost of pushing the items one at a time (at most floor(log2(i + 1)) swaps for the item pushed into slot i, so Theta(n log n) in total) beside it.
  4. Time n hand-written pushes against heapify at 100,000 items on random and on descending input, and decide only from printed ratios.
Q14A Max-Heap By Flipping The ComparisonEasy

A max-heap keeps the largest item on top: no item is larger than its parent. It is the min-heap with both comparisons flipped. In sift_down_max(a, i, n) the item at slot i swaps with its larger child while that child is larger, and is_max_heap(a) fails when a parent is smaller than a child. Build a max-heap from any list with the same loop as heapify: sift down every slot that has a child, from slot n // 2 - 1 back to 0.

  1. Write heapify_max with sift_down_max and is_max_heap and check, on every list in BED (every order of 0..k-1 for k = 0 to 7 and every list over 0, 1, 2 of length 0 to 7), that the result is a max-heap with the same items and that popping (swap the top with the last slot of the heap, shrink the heap by one, sift down) returns the items in descending order.
  2. For numbers there is a second way: store -x in a min-heap, since the smallest -x is the largest x. Check that the two ways pop the same values on 300 seeded lists that hold negatives and zero.
  3. A student flips the "move down" comparison but still picks the smaller child (B14 in the code). Find the smallest list it breaks and print it beside the truth.
Q15The Height Is Always SmallEasy

A heap is stored as a complete tree: every level is full except the last, which fills from the left. So its shape depends only on the number of items n, never on their order, and it has n.bit_length() levels (that is floor(log2(n)) + 1; the empty heap has 0). A search tree built from sorted keys was as tall as the input (DSA Topic 14); a heap cannot be, so a push or a pop never needs a rebalancing step. A push moves one item up and a pop moves one item down, one swap per level.

  1. Print the levels of a heap of 100,000 and of 1,000,000 items, and assert n.bit_length() equals floor(log2(n)) + 1 for every n below 100,000.
  2. Build 100 items by pushes in ascending, descending and random order and print how many slots each level holds: the three shapes must be identical.
  3. With counted copies of push and pop (swaps counted in them, never timed), assert that the most swaps in any single push of 100,000 descending items is at most 16, and the most swaps in any single pop while emptying 20,000 items is at most 14. Each is also at most floor(log2(n)) for the heap size n at that moment.
Q16HeapsortMediumMust Do

Heapsort sorts a list a in place (it returns None, as list.sort() does) into ascending order using a max-heap (no item is larger than its parent; the parent of slot i is (i - 1) // 2 and its children are 2 * i + 1 and 2 * i + 2). Phase one turns the list into a max-heap by sifting down every slot that has a child, from slot n // 2 - 1 back to 0. Phase two repeats: swap the top a[0] (the largest) with the last slot of the heap, a[end], shrink the heap to a[0:end] so the sorted tail is never touched again, and sift the new top down inside a[0:end]. The helper sift_down_max(a, i, n) swaps a[i] with its larger child while that child is larger, looking only at slots below n. It uses < only, needs O(1) extra space and runs in O(n log n) time in the worst case: Theta(n log n) on distinct items in any order, but only O(n) when all items are equal (strict < never swaps equal items). The helpers sift_down_max, Key (a wrapper whose < counts itself), best_of (the smallest time of 3 runs), random_list and the lists BED (every order of 0..k-1 for k = 0 to 7 plus every list over 0, 1, 2 of length 0 to 7) are written out in the answer.

  1. Write heapsort(a) and check it against sorted() on every list in BED and on 300 seeded random lists of 0 to 300 items (plus sorted, reverse-sorted and all-equal lists).
  2. A student sifts with len(a) instead of the shrinking end (B16 in the code), dragging the sorted tail back into the heap. Find the smallest list it fails on and print it beside the truth.
  3. Count comparisons per n * log2(n) for heapsort and for sorted() on random lists, and on an already sorted list of 10,000 items (sorted() finds the run, DSA Topic 9). Then time heapsort against sorted() at 100,000 random items and decide from the printed ratio.
Q17Heapsort Is Not StableEasy

A sort is stable when records with equal keys keep their input order (DSA Topic 9). Heapsort swaps the top with the last slot of the heap, which carries an item far past its equals, so it should not be. Write heapsort_by(records, key): heapsort in place on key(record) alone, comparing keys with < only.

  1. Sort records = [(key, label), ...] by key alone and show two records with the same key coming out in reverse order. Find the smallest such list by a plain scan.
  2. Label every list over the keys 0, 1, 2 (lengths 0 to 7, 3,280 lists) by its positions and count the lists where heapsort leaves equal keys out of arrival order, against sorted(key=) for the same lists.
  3. The fix when order among equals matters: sort (key, position) pairs, so no two keys are equal. Count the lists that still fail.
Q18A Heap Of TuplesEasy

Tuples compare field by field (DSA Topic 9's tuple keys): (1, "backup") < (1, "write") looks at the first fields, and only when they are equal at the second. So a heap of (priority, name) tuples pops by priority and breaks ties by name, not by arrival. A comparison that reaches the second field is a tie-break.

  1. Push (1, "write"), (1, "backup"), (1, "email") (in that order) into a min-heap and print the pop order beside the arrival order.
  2. Count how often the names are compared by wrapping each name in Key, a wrapper that counts its own <: with every priority different the count must be 0, and with ties it is above 0.
  3. Check the pop order against sorted() of the tuples on 300 seeded lists.

A tie-breaker that keeps arrival order comes later in this topic.

Q19Objects That Compare ThemselvesEasy

A heap needs only <: the sift functions never use ==, <=, > or >=. So a class that defines __lt__ alone can go into the heap. An __lt__ that compares priority only is a common first design, and it raises a question about equal priorities.

  1. Write a class Spy that records the name of every comparison method called on it (__lt__, __le__, __gt__, __ge__, __eq__, __ne__), push and pop 50 of them, and print which methods were called.
  2. Write Job with priority and pos (its arrival position) and an __lt__ on priority alone. Scan the lists of priorities over 0 and 1 by length and print the first one whose pop order is not the arrival order among equal priorities, beside the arrival order.
  3. State the lesson from the computed result.
Q20Equal Items Never SwapEasy

sift_up swaps an item with its parent only while it is strictly smaller (<). An item equal to its parent stays where it is. So pushing equal items never moves anything: the heap is built with 0 swaps. A one-character change to <= looks harmless and still gives a valid heap.

  1. With a counted copy of push (swaps counted in it, never timed), push 1,000 equal items with the strict rule and print the swaps.
  2. The bug B20: sift_up with <=, swapping equal items. Push 1,000 and 10,000 equal items and compare the swaps with the sum of floor(log2(i + 1)) over the slots i (an item pushed into slot i climbs to the root), asserting they match.
  3. Show that both versions pass is_heap, so only the count shows the bug.

Strict < keeps equal items in place, but equal priorities still do not leave in arrival order: that is a separate problem, shown earlier in this topic with objects compared on priority alone.

Q21Changing A PriorityMedium

A job in a priority queue changes its priority: the item in slot i of a min-heap must now hold new. Rewriting the slot alone can break the heap, so the heap has to be restored, and only one direction can be needed.

  1. Write find(a, x), the index of the first slot holding x (or None), and say what it costs: a heap is only partly ordered, so finding an item is a scan.
  2. Write change_at(a, i, new): set a[i] = new in place, then sift up if the item got smaller and sift down if it got larger. Trace it on a heap of 8 items with one change in each direction, printing levels after each.
  3. Check over every heap in the 9,194 small lists of the answer (all orders of up to seven distinct items and all lists over 0, 1, 2) that, for every index and every new value from -1 to n + 1, the result is a heap holding the right items. Count the cases in which a sift up and a sift down would both have moved the item (the claim is that it never happens).
  4. Show the student bug that always sifts down, on the smallest failing case found by a scan in order of size, beside the truth, and assert that it fails.
Q22Removing Any ItemMedium

A pop removes the minimum. Sometimes you must remove an item from the middle: a job is cancelled and sits in slot i. The usual trick is to fill the hole with the last item of the list, which keeps the tree complete, and then repair the heap.

  1. Write remove_at(a, i): remove and return a[i] in place, moving the last item into slot i and sifting. Decide which way to sift and say why one direction is not enough (the moved item came from another branch). Trace it on a heap of 6 items.
  2. Check on every heap in the 9,194 small lists (all orders of up to seven distinct items and all lists over 0, 1, 2), removing every index from a fresh copy: the result is a heap holding exactly the other items, and the return value is the item that was in slot i. Count the cases in which the moved item had to climb.
  3. Show the student bug that only sifts down, on the smallest failing case found by a scan in order of size, beside the truth, and assert that it fails.
Q23The k Smallest By PoppingMedium

To get the k smallest items of a list you can sort it and slice, or build a heap and pop k times. The heap does O(n) work to build and O(log n) per pop, so it should win while k is small. Count the comparisons and find where it stops winning.

  1. Write k_smallest(items, k): heap_of(items) then k pops, smallest first. Contract: k <= 0 gives [], and k >= n gives every item, sorted. Check it against sorted(items)[:k] on every list of the answer's 9,194 small lists (all orders of up to seven distinct items and all lists over 0, 1, 2) for every k from -1 to n + 1.
  2. With the Key wrapper that counts every <, count the comparisons for n = 10,000 distinct random items: heapify plus the first k pops, for k = 1, 10, 100, 1,000 and 10,000, beside the comparisons of one sorted() of the same items.
  3. Find the smallest k in 1, 2, 4, 8, ... (by doubling) at which popping makes more comparisons than sorting, and print it as a share of n.
  4. Conclude from the printed numbers only. (DSA Topic 9's top k by sorting, selecting or scanning is the starting point; keeping only k items while a stream arrives is the next level of this topic.)
Q24Memory: An Array, Not NodesEasy

A heap is a tree, but Python stores it as a flat list. Measure what that saves against drawing the same heap as linked nodes, and what the entries themselves cost once they are tuples.

  1. Build the values and the strings before tracing, so that only the structure is counted. With tracemalloc, measure a heap of 100,000 ints built by 100,000 pushes: bytes per item.
  2. Measure a heap of linked nodes with val, left, right and parent references, built from that heap's array (the temporary list that holds the nodes while they are linked is gone before the measurement). Print bytes per item and the ratio to the array.
  3. Measure the bytes per entry of a list of plain ints, of (int, str) pairs and of (int, int, str) triples (the middle int is a counter made while building, so it is almost always a new object). Print sys.getsizeof of an int, a 2-tuple, a 3-tuple and a node beside them.
  4. State the node-to-array ratio from the printed numbers.
Q25What A Heap Does Not KnowMedium

A heap answers one question fast: what is smallest. It is only partly ordered, so almost anything else is a scan. Measure how little of it you can skip.

  1. Write find_in_heap(a, x) returning (index or None, slots visited). Walk from the root with a stack. Stop at x. Never go below a slot holding something larger than x (everything under it is larger too): only a slot holding an item smaller than x opens its two children.
  2. On a heap of 10,000 distinct random numbers, search for six values: the minimum, the item with 100 smaller ones, the median, the maximum, an absent value in the middle and an absent value above the maximum. Let c count the items smaller than x; print the visits and assert visits <= 2c + 1.
  3. Show that the maximum is one of the leaves, a[n // 2:], for every heap in the answer's 9,194 small lists (all orders of up to seven distinct items and all lists over 0, 1, 2).
  4. Show the student bug that takes the last item a[-1] as the maximum, on the first failing heap in a scan by size.
  5. Show that the array is not sorted, so the k-th smallest costs k pops.
Q26Top-k Largest With A Size-k HeapMediumMust Do

Write top_k_largest(stream, k): it reads an iterable of comparable items in one pass, never stores more than k of them, and returns the k largest, largest first. The trick is a min-heap of at most k items holding the largest seen so far. A min-heap keeps its smallest item at the root (a[0]), and each item is at least as large as its parent. Here the root is the weakest of the k kept items, so a new item that is larger than the root replaces it, and anything else is dropped.

Contract: k <= 0 gives []; fewer than k items in the stream gives all of them; equal items are all kept if they are among the largest; the input is not modified. The helpers sift_up, sift_down and MinHeap (a min-heap in a Python list with push, pop and peek) are written out in the answer, and so is Key, a wrapper that counts every < between two items so that comparisons can be counted.

  1. Write top_k_largest with the size-k min-heap: push until it holds k items, then compare each new item with the root, and replace the root (set a[0], sift down) only when the new item is larger. State time and space.
  2. Check it against sorted(data, reverse=True)[:k] on every list of the answer's 9,194 small lists (all orders of up to seven distinct items and all lists over 0, 1, 2) for every k from -1 to n + 1, and on 300 seeded streams fed as generators (so the list is never available), counting the contract cases hit.
  3. Count comparisons per item with Key on 50,000 random items for k = 10, 100 and 1,000, and on 50,000 ascending items (every item replaces the root) for k = 100. Use a counted copy that also counts replacements, and check it returns what the plain function returns.
  4. Show the student bug that keeps a max-heap of the k items (its root is the largest), on the smallest failing input found by a scan, beside the truth.
Q27The k-th Largest In A StreamEasy

A game shows the score of the player in 3rd place after every new score. Build a class KthLargest(k) with add(x) that returns the k-th largest score so far (1-based: k = 1 is the maximum), or None until k scores have arrived. It uses the size-k min-heap of the previous question (kept items are the k largest; the root is the smallest of them, which is exactly the k-th largest).

  1. Write the class. k < 1 raises ValueError. Each add costs O(log k) and the object holds O(k) items however long the stream is.
  2. Check after every add against a sorted list of everything so far (kept with insort), on 300 seeded streams with duplicates for k = 1, 3 and 10. Count the adds that returned None and the adds that did not, and print the largest the heap ever got.
  3. Feed 100,000 scores to KthLargest(3) and print the heap's size at the end.
Q28The k Closest PointsMedium

Given points (x, y) and a target, return the indices of the k points closest to the target, nearest first. Ties go to the smaller index. Use integer squared distances: they order points exactly as true distances do, and integers are exact, so no sqrt is needed.

The farthest of the kept points must be the first to leave. That is a max-heap on (squared distance, index); a min-heap stores it by negating both fields, so its root is the farthest kept point (and, among equals, the one with the larger index).

  1. Write k_closest(points, target, k). k <= 0 gives [], and k >= n gives every index. State time and space.
  2. Check against sorting all indices by (squared distance, index) on 300 seeded point sets with coordinates in -3..3 (many points tie), for a random k from -1 to n + 1. Count how many sets had ties at the cut.
  3. Print one small example with its squared distances. (DSA Topic 3's k closest on a sorted list and DSA Topic 14's k closest keys in a search tree solve the one-dimensional version; a heap does not need sorted input.)
Q29Merging k Sorted ListsMediumMust Do

Write merge_k(lists, key=None): given k lists that are each already sorted ascending (by key of each item, or by the items themselves when key is None), return a new list holding all N items in sorted order. The input lists are not modified. k = 0 or all lists empty gives []. Equal keys must come out in list order (a stable merge: all equal items of list 0, then list 1, and so on, each list's own order kept).

The method: put the first item of every non-empty list in a min-heap as the entry (key, list number, position). Pop the smallest entry, output its item, and push the next item of the same list if there is one. Each item is popped once and pushed at most once, so the heap never holds more than k entries. The list number settles equal keys, and because only one entry per list is ever in the heap, no two entries tie. The helpers sift_up, sift_down and MinHeap (a min-heap kept in a Python list: push, pop, peek, each item at least as large as its parent, compared with <) are written out in the answer, and so is Key, a wrapper that counts every < between two items.

  1. Write merge_k with the heap. State time and space with N items in k lists.
  2. Check against sorted(chain(*lists)) on 300 seeded inputs that include empty lists, a single list, no lists and duplicates across lists.
  3. Show stability: merge three lists of words by key=len and compare with sorted(chain(*lists), key=len), which is stable.
  4. Count comparisons per item at N = 20,000 distinct random numbers split over k = 2, 10, 100 and 1,000 sorted lists (wrap the numbers in Key), beside 2 * log2(k), and assert the count stays within 3 * log2(k) + 1 per item. DSA Topic 12 merged k lists by scanning every head and by halves; DSA Topic 13's tournament bracket is the other tree of winners.
Q30Merging Iterators LazilyMedium

A merge of k sorted iterators must not read them whole: some of them never end. Write a generator merge_lazy(iterables) that holds one entry (value, i, iterator) per source in a min-heap, yields the smallest value, and only then asks that source for its next item. The index i is unique, so two equal values never make Python compare two iterators.

  1. Write merge_lazy(iterables, stats=None); when stats is a dict it records the peak number of entries held. Check against sorted on 300 seeded inputs of lists, tuples and iterators, with empty sources and duplicates, and assert the peak never exceeds k.
  2. Merge 1,000 endless generators (generator j yields j, j + 1000, j + 2000, ...) and take the first 10 items with itertools.islice. Count the items pulled out of the generators, and assert at most k + 10.
  3. Show the student bug that stores (value, iterator): find the smallest failing input by a scan and print the error message. Never print an iterator.
  4. One line: the merge function of the heapq module does this, later in the topic.
Q31The Stable Priority QueueMediumMust Do

A priority queue hands out the item with the smallest priority first. A stable one hands out items of equal priority in the order they arrived (first in, first out). A binary min-heap of (priority, item) pairs settles a tie in priority by comparing the items, which may not be comparable at all. The fix is a third field: entries are (priority, n, item), where n comes from itertools.count() (0, 1, 2, ... one number per push, never repeated). Two entries can never tie on the first two fields, so a tie on priority is settled by n and the item is never compared.

Some helpers are written out in the answer: MinHeap (a binary min-heap in a list, with push, pop, peek and len, comparing items with < only, and an IndexError when it is empty; sift_up and sift_down are its two moves), and ListPQ (the brute-force queue: an unsorted list whose pop scans for the first smallest item, so it is stable by construction).

  1. Write StablePQ with push(priority, item), pop() (returns (priority, item)), peek(), len, and an IndexError when it is empty. Push five tasks, three of them with the same priority, and print the pop order beside the arrival order.
  2. Show why the counter is not optional. First scan lists of priorities 0 and 1 by length, pushing (priority, dict) entries, and print the first list that raises and which push raised. Then build the entries as (priority, item) with a dict as the item and push them into a MinHeap: find, by running the pushes, which push of priorities 5, 4, 3, 2, 1, 1 raises TypeError, and which operation fails for priorities 1, 2, 2 pushed and then popped. Give each dict its own content ({"n": 0}, {"n": 1}, ...): two equal dicts would compare equal, and a tuple of equal fields never asks for <. Print both numbers as computed.
  3. Check StablePQ against ListPQ on 300 seeded scripts of pushes and pops with priorities 0 to 3, and count the pops that hit an empty queue. ListPQ holds a small wrapper that compares priority alone, so its scan decides every tie by arrival.
Q32Highest Priority First, Still FIFOEasy

Many systems call a larger number more urgent (priority 9 before priority 1), but a min-heap serves the smallest key first. For numbers the fix is to store the priority negated: push (-priority, n, item), where n is the arrival counter, and the smallest key is the largest priority. The counter must stay as it is: equal priorities should still leave in arrival order (first in, first out).

  1. Write UrgentPQ on the stable queue: push(priority, item) stores -priority, and pop() returns (priority, item) with the original sign. The stable queue StablePQ (a min-heap of (priority, n, item) entries) and its helpers are written out in the answer.
  2. Write BrokenUrgentPQ that negates the counter as well, (-priority, -n, item), and find by a plain search the smallest script of pushes (priorities 0 and 1, then drain) where it serves a different order than UrgentPQ. Print both orders.
  3. Check both against ListPQ (an unsorted list whose pop scans for the smallest item) fed (-priority, n), on 300 seeded scripts of pushes and pops with priorities 0 to 3.

Numbers only: strings have no minus sign, so a heap of strings needs another trick, later in this topic.

Q33The Running Median With Two HeapsMediumMust Do

After each new number arrives, report the median so far: the lower median, the item at index (n - 1) // 2 of the n items sorted (for 1, 3, 4, 8 that is 3, not 3.5 and not 4). Keep the smaller half in a max-heap low and the larger half in a min-heap high. A max-heap is a min-heap of negated values (-x is pushed, and the top is negated back). The halves obey two rules: len(low) == len(high) or len(low) == len(high) + 1, and no item of low is larger than any item of high. Then the median is the top of low. To add x, push it onto one side, then move at most one top across to restore the sizes. That is at most three heap operations (a push, a pop and a push), so each add costs O(log n) for n items held. Peeking a top is not counted.

Some helpers are written out in the answer: MinHeap (a binary min-heap in a list with push, pop, peek and len, comparing with < only; sift_up and sift_down are its two moves), random_list(n, rng, span) (exactly n random ints below span), and the lists PERMS (every order of 0..k-1 for k = 0 to 7), DUPS (every list of length 0 to 7 over 0, 1, 2) and BED (both together, 9,194 lists).

  1. Write RunningMedian with add(x) (returns the median so far), median() (an IndexError while empty) and a count of the heap operations of the last add. Trace [5, 15, 1, 3, 2, 8]: print the median and both halves after each add.
  2. Write BrokenMedian, which moves items from low to high only and never back. Find on BED, shortest list first (orders before lists with repeats at each length), the first stream where it differs from the truth, and print both answers.
  3. Check RunningMedian against a sorted list kept with bisect.insort (DSA Topic 5's sliding median kept its window that way, and DSA Topic 14 found the lower median of a changing set with select) on every list of BED read as a stream, and on 300 seeded streams, ascending and descending ones included. After every add, assert the size rule, the order rule and the three-operation bound.

The timing of two heaps against insort comes later in this topic.

Q34The Smallest Free IdEasy

An id allocator hands out whole-number ids (think connection numbers or table slots). allocate() returns the smallest id not currently in use, and release(i) frees id i so that it can be handed out again; releasing an id that is not in use raises ValueError. Keep the freed ids in a min-heap. When the heap is empty, every id below next_id is in use, so hand out next_id and add one to it. When the heap has items, its smallest item is below next_id and is the smallest free id. Both calls cost O(log n) for n freed ids waiting in the heap.

  1. Write IdAllocator with allocate and release, on the hand-written MinHeap (a binary min-heap in a list with push, pop and len, comparing with < only; sift_up and sift_down are its two moves), written out in the answer. Trace a short script.
  2. Write BruteIds, which scans 0, 1, 2, ... for the first id that is not in a set of ids in use.
  3. Check the two against each other on 300 seeded scripts of allocate and release, where some releases name an id that is not in use. Count the reused ids and the ValueErrors.
Q35The Last Stone StandingEasy

Stones with whole-number weights are smashed in rounds. Each round takes the two heaviest stones, x <= y. If x == y both vanish; otherwise a stone of weight y - x goes back. When at most one stone is left, return its weight (0 if none is left). Each round needs the largest item of a changing collection, so use a max-heap: a min-heap of negated weights. Each round makes at most three heap operations (two pops and one push), and every round removes at least one stone from the pile, so there are at most n - 1 rounds for n stones.

  1. Write last_stone(stones) on the hand-written MinHeap (a binary min-heap in a list with push, pop, peek and len, comparing with < only; sift_up and sift_down are its two moves), written out in the answer. Return the weight, the number of rounds and the most heap operations any round used. Trace [2, 7, 4, 1, 8, 1].
  2. Write last_stone_sorted, the oracle: a sorted list where each round pops two from the end and insorts the difference.
  3. Check them against each other on every list of BED read as stone weights (all 9,194 lists of up to seven stones with weights 0 to 6; a weight of 0 is allowed) and on 300 seeded lists. Assert the round and operation bounds on every one.
Q36The k-th Smallest In A Sorted MatrixHard

A matrix of R rows and C columns has every row ascending and every column ascending (equal values are allowed). Find its k-th smallest value, counting from 1 (k = 1 is the smallest cell), without flattening and sorting it. Push the first cell of every row into a min-heap as (value, row, column). Pop the smallest cell, and push its right neighbour if there is one. The k-th pop is the answer. k outside 1..R*C raises IndexError.

No record of cells seen is kept, and none is needed. Two lines argue it, and the answer states them as comments: a cell in column 0 is pushed once at the start, and a cell in column c > 0 is pushed only when its left neighbour is popped, which happens once, so no cell enters the heap twice. And every cell not yet pushed is at least as large as its left neighbour, which is in the heap or already popped, so the heap's smallest entry is the smallest cell not yet popped. The heap never holds more than R cells, and pushes number at most R + k.

  1. Write kth_smallest(matrix, k) on the hand-written MinHeap (a binary min-heap in a list with push, pop and len, comparing with < only; sift_up and sift_down are its two moves), written out in the answer. Return the value and the number of pushes, and give it an optional log list that every push appends (row, column) to (it is never read by the search). Trace a 3 x 3 matrix.
  2. Write kth_broken, which pushes both the right and the lower neighbour with no record, so a cell can enter twice. Find by a plain search the first small matrix (distinct values 0 to R*C - 1, sizes from 1 x 1 up to 3 x 3) and k where it gives a different answer from the truth, and print both.
  3. Count the cells each method looks at on a seeded 100 x 100 matrix for k = 1, 100 and 5,000: the heap's pushes, against the binary search on the value that counts cells at or below a value with a staircase walk (DSA Topic 3's count-based search, written out here for R x C matrices) and reads one cell per step.
  4. Check the heap against sorted(all cells)[k - 1] on 300 seeded matrices, k out of range included. Assert that no cell was pushed twice and that pushes stay at or below R + k.
Q37The k Smallest Pair SumsHard

Two lists a and b, each ascending (equal values allowed), give the pairs (i, j) with sum a[i] + b[j]. Find the k pairs with the smallest sums, ties broken by (i, j) (smaller i first, then smaller j), and return them as index pairs in that order. If there are fewer than k pairs, return all of them; k <= 0 or an empty list gives [].

Think of row i as the pairs (i, 0), (i, 1), ...: their sums only grow. Start the heap with (a[i] + b[0], i, 0) for each i < min(k, len(a)). Rows from k on cannot matter: pair (i, 0) has the i pairs (0, 0) to (i - 1, 0) ahead of it. Pop an entry, record (i, j), and push (a[i] + b[j + 1], i, j + 1) if it exists. This takes O(k log k) time and an O(k) heap, and no record of pairs seen is needed: pair (i, j) with j > 0 has exactly one predecessor, (i, j - 1), and is pushed only when that one is popped.

  1. Write k_smallest_pairs(a, b, k) on the hand-written MinHeap (a binary min-heap in a list with push, pop and len, comparing with < only; sift_up and sift_down are its two moves), written out in the answer. Return the index pairs, the number of pushes and the largest the heap grew. Trace a = [1, 7, 11], b = [2, 4, 6], k = 5.
  2. Check it against the brute force that sorts every pair by (sum, i, j) and takes the first k, on 300 seeded inputs: empty lists, a single pair, all-equal lists, many repeats and k larger than len(a) * len(b) included.
  3. Assert on every input that pushes are at most min(k, len(a)) + k and that the heap never holds more than min(k, len(a)) entries.
Q38heapq: The Library HeapMediumMust Do

Python's standard library has a heap module, heapq. It keeps a plain list as a binary min-heap (no item is smaller than its parent, and the smallest is at index 0) in the same array layout as a hand-written heap. The functions take the list as their first argument: heapq.heappush(h, x) adds x; heapq.heappop(h) removes and returns the smallest (an IndexError on an empty list); heapq.heapify(h) rearranges a list in place into a heap and returns None; and h[0] peeks at the smallest item. Everything compares items with <.

Some helpers are written out in the answer: MinHeap (a hand-written binary min-heap in a list with push, pop and len, built on sift_up and sift_down), the hand-written heapify, is_heap (True when no item is smaller than its parent), random_list(n, rng, span) (exactly n random ints below span), best_of(fn) (the smallest wall time of 3 runs), and the lists PERMS (every order of 0..k-1 for k = 0 to 7), DUPS (every list of length 0 to 7 over 0, 1, 2) and BED (both together, 9,194 lists).

  1. Show the four calls on a small list, then run 300 seeded scripts of pushes, pops and "extend, then heapify" on a heapq list and a MinHeap side by side. Assert that is_heap holds after every heapq call and that both give the same value at every pop (or both raise IndexError).
  2. On heapq, compare pops, never arrays: with repeated items the two heaps can hold different arrays and still pop alike. For every list of BED, count the lists where heapq.heapify and the hand-written heapify leave different arrays (separately for orders and for lists with repeats), print the smallest one, and assert that the pop sequences are equal on all of BED.
  3. Time heapq against the hand-written heap at 100,000 random ints, taking the smallest of 3 runs of best_of: pushing all of them, popping all of them, and heapify of a copy. Print each ratio, and draw a verdict only from a printed ratio of at least 2.
  4. Say why, from what the module holds: which of its functions are C functions in CPython and which are Python code. Then name what heapq cannot do, so that a hand-written heap is still needed (decrease-key and d children per node, both later in this topic), and where items with no natural < go instead.
Q39No Max-Heap In heapq: NegateEasyMust Do

Python's heapq module keeps a plain list as a binary min-heap: heapq.heappush(h, x) adds x, heapq.heappop(h) removes and returns the smallest item (an IndexError on an empty list), and h[0] is the smallest item. In Python 3.13 it has no max-heap functions. For numbers the fix is to negate: push -x, and negate again on the way out, since the smallest -x is the largest x. Python 3.14 added public max-heap functions to heapq (heappush_max and its relatives), so the answer asks the running Python whether it has them and builds its sentence from that answer. It never calls the private helpers _heapify_max and _heappop_max, which are not part of the module's API.

  1. Print hasattr(heapq, "heappush_max") and build one sentence from it that says whether this Python needs the negation trick.
  2. Write MaxHeapQ on a heapq list for numbers: push(x), pop() (the largest), peek() (the largest, left in place), len, and an IndexError when it is empty. Trace pushes of 3, 1, 4, 1, 5, printing the stored list beside the items popped.
  3. Show that negation is for numbers only: -"abc" and -("a", "b") raise TypeError. Catch both and print the messages.
  4. Write BrokenMaxHeapQ, whose pop forgets to negate back. Find by a plain search, over lists of -1, 0 and 1 from the shortest up, the first list where it differs from the truth, and print both pop orders.
  5. Check MaxHeapQ against sorted(items, reverse=True) on 300 seeded lists that hold negative numbers and zero, an empty list, a single item, sorted, reverse-sorted and all-equal lists among them.
Q40nlargest And nsmallestMedium

heapq.nlargest(k, iterable, key=None) returns the k largest items as a list, largest first, and heapq.nsmallest(k, iterable, key=None) the k smallest, smallest first. They are documented as equal to sorted(iterable, key=key, reverse=True)[:k] and sorted(iterable, key=key)[:k]: the same items in the same order, items with equal keys included (they keep their input order). For k <= 0 they return [], and for k at least the length they return everything, sorted.

  1. Check the equivalence on 600 seeded inputs (300 for each function) with a key= function and many tied keys: items are (key, id) pairs, compared by key alone through key=lambda p: p[0], so the id shows whether ties keep their input order. Include k below 1 and above the length, an empty input, a single item, sorted, reverse-sorted and all-equal inputs, and count each.
  2. In CPython these two are written in Python (Lib/heapq.py), not C, and they take shortcuts: min or max when k is 1, and sorted() when k is at least the number of items. Count comparisons with the Key class (it counts every < between two keys; counting is for counting only, never for timing) to see them: nsmallest(1, xs) and nlargest(1, xs) against n - 1, and nsmallest(n, xs) against sorted(xs).
  3. Count comparisons at n = 100,000 random items for nlargest with k = 10, 100 and 1,000, against sorted() of the whole list, and for nlargest(10) on ascending input (every new item beats the smallest kept one). Print each count as a multiple of n.

When each one is faster, in time rather than in comparisons, is measured later in this topic. The helper Key and random_list(n, rng, span) (exactly n random ints below span) are written out in the answer.

Q41Push-Then-Pop And ReplaceMedium

heapq has two calls that do a push and a pop in one go. heappushpop(h, x) pushes x, then pops and returns the smallest item: if x is not larger than the top, it comes straight back and the heap is untouched. heapreplace(h, x) pops the smallest item first, then pushes x: it returns the old top even when x is smaller, so the result can be larger than the new top. Each is one call that sifts once, where a push followed by a pop is two calls and two sifts.

  1. Show both on [3, 5, 9] with x = 1 (and heappushpop with x = 7): what each returns and what each leaves behind.
  2. Print the edge cases: heappushpop([], 5) returns 5; heapreplace([], 1) and heappop([]) raise IndexError (print the message).
  3. Check both against their two-call versions (push then pop; pop then push) on 300 seeded scripts that mix pushes, pops, heappushpop and heapreplace, starting from an empty heap, a single item, sorted, reverse-sorted, duplicate-heavy and random lists. Compare the returned values and the pop order of what is left (two correct heaps with repeats can hold different arrays), and check the heap property after every step. Count the scripts of each kind and catch every Exception as a failure.
  4. Count comparisons on 10^4 operations against a heap of 1,000 items (through a counting wrapper), for random x and for an x below every item, each against its two-call version. State the saving from the counts.
Q42heapq.mergeMedium

A hand-written lazy k-way merge from earlier in this topic keeps one entry per input in a heap. heapq.merge(*iterables, key=None, reverse=False) is the library version: a lazy generator that holds one item per input, and a stable merge: equal items (equal keys, with a key) come out in input order, the first input's first. It trusts that every input is already sorted and checks nothing.

  1. Merge two lists of (word, source) records with key=len and show that equal lengths come out with input A before input B, and the other way round when the inputs are swapped. Assert it equals sorted(chain(a, b), key=len).
  2. Check merge against sorted(chain(...)) on 300 seeded cases of 0 to 5 sorted inputs (with and without a key, with duplicates, empty inputs, one input and all-equal items). Count how many cases hit each kind and catch every Exception as a failure. One line: with reverse=True every input must be sorted largest first (its trap comes later in this topic); print that the merge of two descending lists matches sorted(..., reverse=True).
  3. Merge k endless generators (generator j yields j, j + k, j + 2k, ...) for k = 10, 100 and 1,000, take the first 10 items with itertools.islice, and count the items pulled out of the generators.
  4. A student's bug (B42 in the code): trusting merge with an input that is not sorted. Find the smallest failing pair of lists (lists of up to 3 items over 0, 1, 2; a plain scan, shortest first) and print it beside the truth. Then write checked_merge, a generator that raises ValueError at the first descent in any input, and show it on that pair and on every pair in the scan.
Q43A Priority Queue Class On heapqMedium

The stable priority queue from earlier in this topic (a smaller priority leaves first, equal priorities in arrival order, entries (priority, n, item) so items are never compared) kept its entries in the hand-written heap. PQ is the same class on heapq: heappush and heappop on a plain list, a count() for the numbers. Its contract is the same as StablePQ's: push(priority, item), peek() and pop() return (priority, item), and peek and pop raise IndexError on an empty queue. The scan-based ListPQ (an unsorted list, pop takes the first smallest) is the brute-force oracle. queue.PriorityQueue (thread-safe, heapq behind a lock) and the dataclass recipe in the heapq documentation are named here and not used.

  1. Check StablePQ, PQ and ListPQ agree on 300 seeded scripts of pushes, pops and peeks (all-equal priorities, many ties, spread priorities, and pops on an empty queue). ListPQ holds small objects whose < looks at the priority alone, so its scan is FIFO by construction. Count the scripts of each kind and catch every Exception as a failure.
  2. Time one script of 5 * 10^4 pushes then 5 * 10^4 pops on StablePQ and on PQ: print both times and the ratio, with no verdict (the ratio moves with the machine's load).
  3. Objects whose __lt__ looks at the priority alone are not FIFO in heapq either (a hand-written heap with a priority-only < loses arrival order too, shown earlier in this topic). Scan lists of priorities over 0 and 1, shortest first, for the first whose heapq pop order is not (priority, arrival position), and print it beside the FIFO order. Then check that PQ is FIFO on every such list of up to 7 priorities.
Q44The Smallest Range Covering k ListsHard

You are given k ascending lists. Find the smallest range [lo, hi] that holds at least one item of every list: "smallest" means the smaller hi - lo, and among equal widths the smaller lo. Every list must be non-empty (raise ValueError otherwise, and for no lists at all). The method: keep the current item of each list in a min-heap and the largest of them in a variable. The range [heap minimum, largest] holds one item of every list, so it is a candidate. Pop the minimum, move that list on one item, push its next item (update the largest), and stop when a list runs out: no range later can hold all lists. Each item enters the heap once, so the cost is O(N log k) for N items.

  1. Write smallest_range(lists) with heapq and run it on [[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]] and on a case with equal-width answers to show the tie rule. Print the ValueError for no lists and for an empty list.
  2. Write the brute force: try every pair of values (lo, hi) from the input, narrowest first (smaller lo first among equals), and take the first pair holding an item of every list. Check the heap version against it on 300 small seeded inputs (one list, one item per list, duplicates, equal widths, a single-value answer). Count the cases of each kind and catch every Exception as a failure.
  3. On one larger input, count the passes of the heap loop and the pairs the brute force would try, and assert the passes are at most N.
Q45Sorting A Nearly Sorted ListMedium

A list is k-sorted when every item is at most k places from where it belongs in the sorted order. DSA Topic 9's k-sorted array was sorted by insertion in O(nk). A heap does better: keep a window of k + 1 items in a min-heap. The smallest item of the window is the next output, because everything that belongs before it is within k places and so already in the window. Feed the next item with heappushpop (push it, pop the smallest, which is the next sorted item) and, when the input ends, pop the rest. That is O(n log k) time and O(k) extra space besides the output. Build k-sorted inputs as Topic 9 did, by shuffling each block of k + 1 consecutive sorted values, and assert the property.

  1. Write k_sorted(n, k, rng) (exactly n items; ValueError for a negative n or k), max_displacement and window_sort(items, k) (a new list; ValueError for k < 0). Print that the property holds on built inputs.
  2. Check window_sort against sorted() on 300 seeded inputs (empty, single, already sorted, k = 0, k >= n, duplicates). Count the cases of each kind and catch every Exception as a failure. Show what happens when k is too small for the input.
  3. At n = 10^5 and k = 10, 100, 1000, count the comparisons of window_sort and of sorted() (through a counting wrapper, checked equal to the plain results).
  4. Time both on plain code and print the ratios (no verdict: a ratio only). Close from the numbers: which made fewer comparisons, and what the window holds.
Q46Reversed Order For Any ItemMedium

heapq is a min-heap, and the usual trick for the largest item first is to push -x. That works for numbers only. For words, tuples or any item you can compare but not negate, write a small wrapper class whose __lt__ is reversed: Rev(a) < Rev(b) exactly when b.v < a.v. A min-heap of Rev objects then pops the largest value first. When only one number inside a tuple needs reversing, negate that number and leave the rest: (-count, word) pops the highest count first and, among equal counts, the alphabetically first word.

Negation fails on strings and tuples, shown earlier in this topic.

  1. Write Rev and check that popping a heap of Rev(word) equals sorted(words, reverse=True) on 300 seeded word lists (empty, single, duplicates, sorted and reverse-sorted lists). Count the lists of each kind and catch every Exception as a failure.
  2. On (count, word) pairs from a Counter of seeded word lists, check the (-count, word) heap against sorted(pairs, key=lambda p: (-p[0], p[1])) on 300 lists, and show on one sample what wrapping the whole pair in Rev would do to the word order. The wrapper's cost in time is measured later in this topic.
Q47Top-k Frequent ItemsMedium

Count with a Counter (DSA Topic 7), then take the k most frequent items. A heap keeps k candidates while u distinct counts go past, so this is O(n log k) in the worst case; DSA Topic 7's top k frequent and DSA Topic 9's buckets did it with counts, sorts and buckets, and this one adds a tie rule: equal counts go to the smaller item. heapq.nsmallest(k, counts.items(), key=lambda p: (-p[1], p[0])) does it: the key sorts by highest count, then by smallest item.

  1. Write top_k_frequent(items, k) and run it on a word list with ties. k <= 0 gives []; k above the number of distinct items gives all of them.
  2. Check it against the oracle that sorts every (-count, item) pair on 300 seeded lists (empty, single, ties, k = 0, k above the distinct count, all equal). Count the cases of each kind and catch every Exception as a failure.
  3. A student's bug (B47 in the code) uses the count alone as the key. Find the smallest failing input by a scan (lists over 0, 1, 2, shortest first, k from 1 to 3) and print it beside the truth. Then show that Counter.most_common(k) leaves ties in first-seen order, like the buggy key (CPython behaviour), on every list of the scan.
Q48Merging Two HeapsHard

heapq has no merge_heaps. Two heaps of N and M items can be joined two ways. Concatenate and heapify: copy both into one list and run heapify, O(N + M). Push the smaller into the larger: M calls of heappush into a heap of N or more items, O(M log(N + M)) in the worst case. The big-O bounds pick heapify for a large M and pushing for a small M, but a push stops as soon as the item is no longer smaller than its parent, so the counts decide.

  1. Write merge_heapify(a, b) and merge_push(a, b) (each returns a new list and leaves both heaps alone). Check both with is_heap, the same items (compared sorted) and unchanged inputs on 300 seeded pairs of heaps (empty, single, duplicates, ascending and descending ones). Count the pairs of each kind and catch every Exception as a failure. is_heap, Key (a value that counts every <) and the lists BED (every order of 0..k-1 for k = 0 to 7 plus every list over 0, 1, 2 of length 0 to 7) are written out in the answer.
  2. Count the comparisons of each on random items, N = 10^4 and M = 10, 100, 1,000, 10^4, and print which is cheaper in each case from the counts.
  3. Count them again when every pushed item is a new minimum and they arrive largest first, for M = 1,000 and M = 10^4, and print the winner of each from the counts.
  4. A student's bug (B48 in the code) concatenates and forgets to heapify. Find the smallest failing pair of heaps from BED (heaps of up to 4 items, shortest total first) and print the result beside the repaired one.
Q49A Heap Built From NodesHard

A heap does not have to live in a list. It can be linked nodes, each with left, right and parent references, as in the linked trees of earlier topics. The one thing the array gave for free is the next free slot, and it comes back from arithmetic: number the slots from 1 in level order, and the binary digits of m after its leading 1 are the path to slot m from the root (0 goes left, 1 goes right). Push puts a new node in slot n + 1 (the parent is slot (n + 1) // 2) and swaps values upward. Pop copies the last slot's value to the root, cuts the last node off and swaps values downward. Values move, nodes stay.

  1. Write HNode and NodeHeap with push, pop and peek (IndexError on an empty heap), and check it against heapq on 300 seeded scripts (empty pops, a single item, duplicates, ascending and descending pushes, peeks). Count the scripts of each kind and catch every Exception as a failure. Never print a node.
  2. Print the path of slots 1, 2, 3, 5, 6 and 11 from the binary digits.
  3. Measure bytes per item with tracemalloc for 3 * 10^4 ints (built first) in a NodeHeap and in a heapq list.
  4. Time n pushes then n pops on NodeHeap and on the hand-written array heap (sift_up, sift_down and MinHeap are written out in the answer) and print the ratio only, with no verdict. Say why the array wins on memory, and name the heaps that do use nodes: leftist, binomial and pairing heaps merge in O(log n), and are named here and not built.
Q50Turning A Min-Heap Into A Max-HeapMedium

You hold a min-heap (no item is smaller than its parent) and need a max-heap (no item is larger than its parent) of the same items. Re-heapify with the flipped sift: sift_down_max swaps an item with its larger child while that child is larger. Sift down every slot that has a child, the last parent first, as heapify does. That is O(n) time and O(1) extra space, in place, and the result is a max-heap: the largest item on top, and pops come out in descending order.

  1. Write to_max_heap(a) (in place, returns None) and check it with is_max_heap on every min-heap in BED (the 540 heaps among every order of 0..k-1 for k = 0 to 7 and every list over 0, 1, 2 of length 0 to 7), including that the items are the same and that popping with pop_max gives sorted(heap, reverse=True). is_heap, is_max_heap, sift_down_max and BED are written out in the answer.
  2. Check it on 300 seeded random min-heaps of 0 to 300 items (empty, single, all equal, ascending, duplicates). Count the cases of each kind and catch every Exception as a failure.
  3. Count the swaps (one swap is one exchange of two slots) against n - popcount(n), the sum of the heights of the slots, for ascending lists of 1 to 1,999 items (an ascending list is already a min-heap) and for every min-heap in BED, and print how often the bound is met exactly.
  4. A student's bug (B50 in the code) just reverses the array. Find the smallest min-heap in BED (shortest first) whose reversal is not a max-heap and print it beside the truth.
Q51Decrease-Key With An Index MapHardMust Do

A priority queue often has to change the priority of an item it already holds: a job is bumped up, a price drops. Finding the item in a plain heap array is a scan, O(n). The fix is an index map: a dict pos from each item to the slot it sits in, kept right every time an entry moves. heapq has no such operation (it keeps no map), so this is a heap you write yourself.

Build IndexedHeap, a binary min-heap in a list a (slot i has parent (i - 1) // 2 and children 2 * i + 1, 2 * i + 2). Each slot holds a tuple (priority, item), compared as a whole, so a smaller priority wins and equal priorities go to the smaller item. Items are unique and hashable (and comparable with each other); priorities are numbers.

  • push(item, priority): ValueError if the item is already held. O(log n).
  • pop(): remove and return the smallest (priority, item); IndexError on an empty heap. O(log n).
  • update(item, priority): give a held item a new priority, smaller or larger, and restore the heap. KeyError if the item is not held. O(log n).
  • Every move goes through one helper _swap(i, j) that exchanges two slots and writes both new positions into pos. Nothing else writes pos except push (new entry) and pop (deleted entry). The helper is_heap(a) (true when no slot is smaller than its parent) and best_of(fn) (the smallest time of 3 runs) are written out in the answer.
  1. Write the class and trace six items through a push, an update that sinks an item and an update that lifts one, printing the array and pos.
  2. Check against a brute-force dict from item to priority (the minimum found by scanning it) on 500 seeded scripts of pushes, pops, updates, missing-item updates, duplicate pushes and empty pops, plus an empty script, a one-item script, ascending, descending and all-equal priorities. After every operation assert pos[a[i][1]] == i for every slot, len(pos) == len(a) and is_heap(a). Count the cases each kind of operation hit, Exception as a failure.
  3. Time 10,000 items and 50,000 random updates (then draining the heap) against lazy re-push: on an update push a new entry onto a heapq list and leave the old one, and when popping skip every entry that is out of date. Print the time ratio (ratio only: it moves from run to run) and count the entries each approach holds at its peak and the out-of-date entries the lazy one pops (say why both counts are fixed by this script: every update comes before any pop). Then run a mixed script of 30,000 steps, about a fifth of them pops, and print the lazy peak, which this time is a real measurement.
  4. One line: the best-known user of decrease-key is Dijkstra's shortest paths (DSA Topic 18). Nothing here walks a network.
Q52Cancelling Entries By MarkingMedium

A job in a priority queue is cancelled while it waits. Removing it from the middle of a heap needs a search and a repair; the heapq documentation's recipe avoids both: mark the entry cancelled and leave it where it is, and skip marked entries when they reach the top. (DSA Topic 11 cancelled an order in a queue by marking it the same way.)

Entries are mutable lists [priority, n, item], where n is a counter that numbers the pushes, so two entries never tie and the item is never compared. A dict finder maps each live item to its entry. Cancelling sets the entry's last slot to the marker REMOVED.

  1. Write CancelPQ on heapq with push(item, priority) (pushing an item that is already live replaces it: the old entry is cancelled), cancel(item) (KeyError if the item is not live), pop() (the live entry with the smallest priority, the earliest pushed among equals, as (priority, item); IndexError when nothing is live), and len() (live items only). Count the stale entries popped and the peak number of entries the heap held.
  2. Check it against a real removal: a ListPQ (an unsorted list popped by a scan) whose cancel deletes the entry from the list. Run 300 seeded scripts of pushes, replacing pushes, cancels, missing cancels, pops and empty pops, plus an empty script, one item, ascending, descending and all-equal priorities, and count each kind of case.
  3. Push 2,000 tasks, cancel 60% of them, then pop everything, and print the peak size, the stale entries popped and the entries left after each. Then replace one item 1,000 times and print how many entries the heap holds for one live item, and what a compact() that rebuilds from the live entries leaves.
  4. A student keys the cancel by priority, so cancelling one task also cancels every other task with that priority (B52 in the code). Find the shortest failing script by a search in order of length and print it beside the truth.
Q53A d-ary HeapMedium

A binary heap has 2 children per slot. A d-ary heap has d: slot i has children d * i + 1 through d * i + d and parent (i - 1) // d. With more children the tree is shallower, so a push (which climbs) makes fewer swaps; but a pop (which sinks) must find the smallest of up to d children on every level, up to d comparisons per level (d - 1 among the children and one against the item).

  1. Write DHeap(d), a min-heap with push, pop and peek; d < 2 raises ValueError, an empty pop or peek raises IndexError. Write is_dheap(a, d) and check, for d = 2, 3 and 4 on every list in BED (every order of 0 to 6 distinct items and every list over 0, 1, 2 of up to 6 items), and for d = 2, 3, 4, 8 and 16 on 200 seeded lists of 0 to 300 items plus empty, one-item, sorted, reverse-sorted and all-equal ones, that after every push (every push for lists of up to 40 items, the last push for longer ones) the array is a d-ary heap and the pops come out as sorted() gives.
  2. Print the number of levels a heap of 10,000 items has for d = 2, 3, 4, 8 and 16 (the smallest L with 1 + d + ... + d^(L-1) >= n).
  3. Count comparisons per item for n pushes followed by n pops of random items, n = 10,000, for those five d (a Key wrapper counts every <; the counted run and the timed run share the class, so time plain integers). Print which d needed the fewest and which the most, from the counts.
  4. Time d = 4 against d = 2 on the same input and print the ratio (ratio only: it moves from run to run).
  5. A student writes the 4-ary sift_up but keeps the binary parent (i - 1) // 2 (B53 in the code). Find the smallest push sequence it breaks (scan the orders of 0 to 6 by length) and print the array and is_dheap beside the truth, then count how many of 300 seeded random lists of 6 to 30 items pop out of order through the broken heap.

Say, without measuring it here, when a d-ary heap pays: a workload with many more priority decreases (each one sifts up, which gets cheaper) than pops.

Q54Top-k: nlargest Or sorted(), MeasuredMediumMust Do

You need the k largest of n numbers. Two library calls do it. heapq.nlargest(k, xs) keeps a heap of the k largest seen so far, so it needs O(n log k) time and O(k) extra space. sorted(xs, reverse=True)[:max(k, 0)] sorts everything (the max matters: [:-1] would drop the last item instead of returning nothing), O(n log n) time and O(n) space. Both return the k largest in descending order, give [] for k <= 0 and every item (sorted) for k >= n; the ratio rows below time sorted() with that slice. In CPython sorted() is C code (Timsort, which finds runs that are already in order), while nlargest is Python code that calls C heap functions, so the bounds alone do not say which is faster. Measure it.

The helpers best_of(fn) (the smallest time of 3 runs) and random_list(n, rng, span) (exactly n random ints below span; ValueError for a bad n) are written out in the answer. Time plain integers.

  1. Check on 50 seeded inputs with duplicates, plus an empty list, one item, ascending, descending and all-equal lists, every k from -1 to n + 1, that the two calls return the same list.
  2. Time both at n = 100,000 random items for k = 10, 100, 1,000, 10,000 and 50,000, and on an ascending input at k = 10. Print each ratio sorted() time / nlargest time. Give a verdict only for k = 10 and for the ascending input, and only when the ratio is at least 2; every other row, k = 100 included, prints the ratio alone, because its gap is small or moves from run to run on a busy machine.
  3. For k = 1, check that max(xs) equals nlargest(1, xs)[0] and print the time ratio (ratio only).
  4. End with lines built from the measured variables: what to call for a small k (from the k = 10 verdict) and for input that may already be sorted (from the ascending verdict). For a large k and for k = 1 print the ratios only, with no recommendation.
Q55heapq.merge Or Sort Everything, MeasuredMedium

You hold k lists that are each already sorted, N items in all, and want one sorted list. heapq.merge(*runs) does the textbook thing: a heap of k entries, O(N log k) time, and it is lazy (an iterator that reads each run only as far as needed). The other call is sorted(chain(*runs)), which throws the sortedness away and sorts all N items, O(N log N); but Timsort (DSA Topic 9) finds each sorted run and merges them in C, and heapq.merge is Python code. Measure which one wins and what each one holds in memory.

best_of(fn) (the smallest time of 3 runs), random_list and Key (a wrapper whose < adds 1 to Key.compares) are written out in the answer.

  1. Build runs: draw N random items first, cut them into k near-equal chunks (the lengths add up to N) and sort each chunk. Check briefly (the full check of heapq.merge against sorting was shown earlier in this topic) that the two calls return equal lists for k = 1, 2, 3, 10 and on 50 seeded inputs plus a few edge cases: no runs, empty runs, one item and duplicates across runs, counting each.
  2. Time both at N = 100,000 for k = 2, 10, 100 and 1,000 and print merge time / sorted time: how many times slower merge is. Give a verdict only for k = 2, and only when the ratio is at least 2; the other k print the ratio alone, because their gaps move from run to run on a busy machine.
  3. Count comparisons per item for both at N = 20,000 and the same four k.
  4. Count the most items each one holds at once at N = 20,000: feed the runs to merge through generators that count how many items they have given out minus how many merge has handed on, and note that sorted() builds a list of all N (the lazy merge earlier in this topic already showed the heap holding at most k entries; here that is set against sorted()). (The external sorter of DSA Topic 9 merged runs from temp files for exactly this reason.)
  5. End with lines built from the measured variables: which to call when everything is already in lists in memory, and which when the input is a lazy stream or does not fit.
Q56The Running Median, MeasuredMedium

A stream of numbers arrives one at a time and after each one you report the lower median of everything so far: the item at index (n - 1) // 2 of the n items sorted. Earlier in this topic the median was kept between two heaps: low, a max-heap of the smaller half (a min-heap of negated values), and high, a min-heap of the larger half, rebalanced so that low holds (n + 1) // 2 items; the median is the top of low. DSA Topic 5 kept a sorted list with insort instead, where each insert shifts the tail (one C memmove, DSA Topic 14), O(n) per item.

  1. Write median_heapq(xs) (two heapq heaps), median_hand(xs) (the same two heaps on the hand-written MinHeap) and median_insort(xs) (insort). Each returns the list of lower medians, one per item. Check all three against sorted(xs[:i + 1])[i // 2] on 300 seeded lists, with an empty list, one item, ascending, descending, all-equal and duplicates.
  2. Time median_heapq against median_insort at 50,000 items, on random input and on descending input, and print how many times faster the heaps are. Give a verdict for the descending input only, and only when the ratio is at least 2; the random-input ratio moves from run to run on a busy machine, so it prints alone.
  3. At 10,000 random items (hand-written pops are slow, so not 50,000) time median_hand, median_heapq and median_insort and print insort / hand-written and hand-written / heapq (ratio only: no verdict).
  4. End with lines built from those ratios: how the heaps did against insort, and how the same idea written by hand did against the library that implements it.
Q57The Sliding Median With Lazy DeletionHard

Report the lower median (the item at index (k - 1) // 2 of the sorted window) of every window of k consecutive items of a list. Two heaps keep a running median, but a heap cannot delete an item from the middle, and the item that leaves the window can be anywhere. Lazy deletion answers that: do not delete it, write it down in a dict delayed (value to the number of copies waiting to go) and throw it away only when it reaches the top of its heap. The sizes used to balance the heaps must then count live items only, kept in two counters beside the heaps.

low is a max-heap of the smaller half (a heapq list of negated values) holding the lower median at its top, high is a min-heap of the larger half, and balance means live(low) equals live(high) or is one more. DSA Topic 5 slid a median across a window with a sorted list and bisect; that is the oracle here.

  1. Write LazyMedian with add(x), remove(x) (x must be in the window; it marks one copy as delayed, adjusts the live counters and prunes both tops) and median(), then sliding_median(a, k) on top of it: ValueError for k < 1, [] when k > len(a). State the time (O(n log n)) and what the heaps can hold.
  2. Check against the bisect sorted-window version on 300 seeded inputs (empty, one item, ascending, descending, all-equal and many duplicates, with k from 1 to n + 1) and count the cases hit.
  3. Print the most entries the two heaps held at once, beside k, for random, ascending and descending lists of 5,000 items with k = 50.
  4. A student balances by the raw heap sizes len(low) and len(high), which still include the delayed items (B57 in the code). Find the smallest input that gives a wrong list, by a scan of BED (every order of up to 7 distinct items, then every list over 0, 1, 2 of up to 7 items) in order of length, and print it beside the truth; count over BED how many outcomes are wrong and how many of those are an exception.
Q58Scheduling By PriorityHardMust Do

One worker runs jobs one at a time. A job is a tuple (id, arrival, length, priority) of integers: id is unique, arrival >= 0 is the minute it becomes available, length >= 1 is how many minutes it runs, and a smaller priority number is more urgent. The rule, exactly:

  • Whenever the worker is free, it starts the waiting job (one with arrival <= now) that has the smallest priority number; ties go to the earlier arrival, then to the smaller id.
  • A started job runs to the end without interruption.
  • If nothing is waiting, the worker waits until the next job arrives (the clock jumps there).

A job's wait is start - arrival. The helper ListPQ (an unsorted list whose pop scans for the smallest item and removes it) is written out in the answer for the brute-force check.

  1. Write schedule(jobs): sort the jobs by (arrival, id), feed them into a heap of (priority, arrival, id) entries as the clock reaches their arrival, and return a list of (id, start, finish, wait) in the order the jobs start. ValueError for a repeated id, a length below 1 or a negative arrival. State the time (O(n log n)) and the space.
  2. Print a schedule for eight jobs that has simultaneous arrivals, an idle gap and two jobs with the same priority, and the average wait.
  3. Check against a brute-force simulation of the same rule that never sorts and never pre-feeds: at each decision it scans every job not yet started, moves those with arrival <= now into a ListPQ, and pops from it, jumping the clock when nothing waits. Use 300 seeded job lists (0 to 12 jobs, arrivals from 0 to 100, lengths 1 to 6, priorities 0 to 2), plus an empty list, one job and all jobs arriving together, and assert on every schedule that no two jobs overlap and none starts before it arrives. Count the cases with simultaneous arrivals, with an idle gap and with a pick that had a priority tie.
  4. This simulates a stated rule. It does not claim the rule is the best one, and whether any rule minimises the waiting is a question for greedy algorithms (DSA Topic 20). One line, then: the round robin with arrivals of DSA Topic 11 was a tick-by-tick simulation of a different rule.
Q59Meeting Rooms With A Heap Of End TimesMedium

Meetings are half-open intervals [start, end) with start < end: a meeting that ends at 10 and one that starts at 10 do not overlap and may share a room. DSA Topic 9 counted the rooms needed with two sorted lists, and its room booker reused the room that frees first by scanning every room for it; the heap replaces that scan, O(log rooms) instead of O(rooms), and also says which room each meeting gets.

The rule: take the meetings in order of (start, end, input position). Before placing one, release every room whose meeting ended at or before the new start (a heap of (end, room) entries; a released room number goes onto a heap of free numbers). Then give the meeting the smallest free room number, or open the next new room (numbered 0, 1, 2, ...) if none is free.

  1. Write assign_rooms(meetings) returning (rooms_used, room_of), where room_of[i] is the room of the i-th input meeting. ValueError if a meeting has start >= end. Print the result for eight meetings that include two touching ones, and state the time (O(n log n)) and space.
  2. Write rooms_by_sweep(meetings), the count from the two sorted lists (starts and ends; a start takes over the earliest unused end if that end is at or before it), and a brute-force assign_brute that keeps the last end of each room in a list and scans the rooms in number order. Check on 300 seeded inputs (0 to 20 meetings, starts 0 to 30, lengths 1 to 8, plus empty, one meeting, all touching and all identical) that the room count equals the sweep, that assign_rooms equals assign_brute, that no room holds two overlapping meetings and that the rooms used are numbered 0 to rooms_used - 1. Count the cases with touching meetings and with equal starts.
  3. A student releases only rooms with end < start (B59 in the code), so a room that frees up at the very minute is not reused. Find the smallest failing input by a search over lists of up to 3 meetings with starts 0 to 3 and ends 1 to 4, and print it beside the truth.
Q60The Event QueueHardMust Do

A help desk has c clerks. A customer is a pair (arrival, service) of integers: they arrive at minute arrival >= 0 and need service >= 1 minutes with a clerk. The rules, exactly:

  • Customers wait in one first-in-first-out line: arrival order, and customers who arrive in the same minute join in list order.
  • A free clerk takes the customer at the front of the line at once, in the same minute.
  • A customer who starts at minute t finishes at t + service, and the clerk is free again from that minute.

An event queue simulates this without ticking through every minute: a heap of events (time, seq, kind, data) where kind is "arrive" or "finish", data is the customer's list position, and seq is a counter that numbers the events as they are scheduled, so two events at the same time are handled in seq order and the tuple never compares kind or data. Time jumps from one event to the next. Handling an event at time t must never schedule anything before t, and the code asserts it.

  1. Write run_desk(customers, c) returning (starts, finishes, handled): each customer's start and finish minute and the number of events handled. ValueError for c < 1, a service below 1 or an arrival below 0. State the time (O(n log n)) and space for n customers.
  2. Print the events of a small day (six customers, two clerks) in the order they were handled, with a pair of events at the same minute, and then each customer's start and finish.
  3. Write run_ticks(customers, c), the tick-by-tick version: for each minute t in turn, append the customers arriving at t to the line, then give the front customer to a free clerk (one whose last customer finishes at or before t) while any clerk is free and anyone waits. It returns the starts and the number of ticks it looped. Check every start time of run_desk against it on 300 seeded days (0 to 15 customers, arrivals 0 to 40, services 1 to 6, one to three clerks), plus an empty day, one customer and a day where everyone arrives in the same minute. Count the days with simultaneous arrivals, with an arrival in the same minute as a finish, with a customer who waited, and the events handled at the same minute as the one before.
  4. Count events handled against ticks looped for a quiet day (40 customers over 100,000 minutes, two clerks) and a busy day (3,000 customers over 1,000 minutes, four clerks). Build the closing lines from those counts. The tick-by-tick simulations of DSA Topic 11 are the cited baseline.
Q61The Cooldown SchedulerHard

Tasks are labelled by capital letters, one slot per task. Two runs of the same letter must have at least n other slots between them (tasks or idle slots; n >= 0, ValueError for a negative n), and a slot may be idle, written .. The rule, stated in full: in each slot, among the letters that still have copies left and whose cooldown has passed, run the one with the most copies left (ties: the alphabetically first letter); if there is none, the slot is idle. The run ends when every copy has run, so the schedule never ends with an idle slot.

The fast version keeps the letters that may run now in a max-heap of (-left, letter) (a min-heap of negated counts, as earlier in this topic) and the letters that are cooling in a deque of (slot it returns, -left, letter). A letter that ran in slot t returns in slot t + n + 1, so the deque is already in order of return slot. Whether this rule gives the shortest possible schedule is not claimed here (that kind of argument is DSA Topic 20); this question simulates the stated rule and checks it.

  1. Write schedule(tasks, n) (a string of letters in, a string of slots out) on the heap and the deque, and schedule_scan(tasks, n), which follows the same rule by scanning every letter in every slot. Write is_valid(tasks, n, out): the same copies of each letter as tasks, and any two runs of one letter at least n + 1 positions apart.
  2. Print the schedule of "AAABBB" with n = 2 and its length.
  3. On 300 seeded inputs (empty, a single task, n = 0, one letter repeated, many letters with a long cooldown so that idle slots appear), check that schedule is valid, never ends with an idle slot, and equals schedule_scan. Count the inputs of each kind and catch every Exception as a failure.
  4. schedule_no_cooldown is the broken version: it puts a letter back into the heap at once and ignores n. Find by a plain search the smallest failing input (strings over AB, shortest first, n from 1 to 2) and print the broken schedule beside the true one.
Q62The k Smallest Of A Heap, Left UntouchedHard

You are handed a min-heap as a list a (every item at least as large as its parent; slot s has children 2s + 1 and 2s + 2, parent (s - 1) // 2) and must list its k smallest items in ascending order without changing a and without sorting it. The method: keep a second heap, the frontier, of (value, slot) pairs. Start it with the root. Pop the smallest pair, output its value, and push the pair for each child slot that exists. The smallest item not yet output is always in the frontier, because every unlisted item has an ancestor that is in it (its parent is listed, or it is the root). Each slot has exactly one parent, so no slot is ever pushed twice and no record of slots seen is needed. Ties between equal values break by the smaller slot, through the tuple. k <= 0 gives [], and k > len(a) gives every item.

is_heap, random_list and the lists BED (every order of up to seven distinct items and every list of up to seven items over 0, 1, 2) are written out in the answer.

  1. Write k_smallest(a, k, stats=None). When stats is a dict it records pops, pushes and peak (the most pairs in the frontier). Check against sorted(a)[:k] that a is unchanged, pops are min(k, n) and pushes at most 2 * pops + 1, for every heap in BED and every k from -1 to len(a) + 1, and on 300 seeded heaps built with heapq.heapify. Count the heaps and k values of each kind and catch every Exception as a failure.
  2. On a heap of 10^5 items count pops, pushes and the frontier's peak for k = 10, 100 and 1,000, assert pushes <= 2k + 1 and peak <= k + 1, and print them beside n.
  3. k_smallest_left_only is the broken version: it pushes only the left child. Find by a plain search over BED (shortest first) the smallest failing heap and k, and print what it does beside the truth.
Q63Sliding Window Maximum: Heap Or DequeMedium

The maximum of every window of k consecutive items of a list a (k >= 1, ValueError otherwise; k > len(a) gives [], since no full window exists) can be found with a heap. Push (-value, index) for each item (a min-heap of negated values, as earlier in this topic). Before reading the top as the window's maximum, drop stale tops: while the top's index is at most i - k (outside the window ending at i), pop it. A stale entry that is not on top is harmless and stays until it surfaces. That costs O(n log n). DSA Topic 11's monotonic deque (indices kept so that their values fall from front to back) does it in O(n), and is written out below as the comparison.

  1. Write window_max_heap(a, k) and window_max_deque(a, k) and check both against the max of each window on 300 seeded inputs (empty, k = 1, k = n, k > n, duplicates). Count the inputs of each kind and catch every Exception as a failure.
  2. In separate counted copies, count the most entries each holds after a step (peak) and the pops (heap pops; the deque's pop and popleft) at n = 10^5 and k = 1,000 on random, ascending and descending input. Assert deque peak <= k and heap peak <= n, and that each counted copy returns what the plain one does.
  3. Time the plain functions on the random input for k = 10 and k = 1,000 (min of 3) and print the ratios with no verdict: they move with the machine's load. Close with a sentence built from the counts.
  4. window_max_heap_if is the broken version: an if that drops the top only when its index is exactly the one leaving the window. Find by a plain search the smallest failing input (shortest first) and print it beside the truth.
Q64Streaming Percentiles With Two HeapsHard

After each new item of a stream, report the p-th percentile of everything seen so far, by nearest rank: with n items seen, the answer is the item of 1-based rank r = (p * n + 99) // 100 in sorted order (p an integer from 1 to 100, ValueError otherwise; the rank is in 1..n). Use two heaps: low, a max-heap (negated values in a min-heap), holds exactly the r smallest items, and high, a min-heap, holds the rest. The answer is the top of low. A new item x goes to high if it is larger than the top of low, otherwise to low; then items move across until low holds exactly r. p = 50 is the lower median, and p = 100 is the maximum.

Why integers: math.ceil(p / 100 * n) looks the same and is not, because p / 100 is not exact in binary.

  1. Write running_percentile(stream, p) and check it against sorting each prefix on 300 seeded streams for p = 50, 90, 99 and 100 (empty, single, sorted, reverse-sorted, all equal and duplicates included). Count the streams of each kind and catch every Exception as a failure.
  2. Count the pairs (p, n) with p in 1..99 and n in 1..1,000 where math.ceil(p / 100 * n) differs from (p * n + 99) // 100. Print the count and the first pair in order of p, then n, with p / 100 * n as Python prints it.
  3. running_percentile_floor is the broken version: it uses max(1, p * n // 100) as the rank. Find by a plain search the smallest failing stream (shortest first, over the lists of 0 and 1, and the orders of 0..3) and print both answers beside the truth.
Q65A Heap Of Objects In Custom Order, MeasuredMedium

heapq compares items with <. There are two ways to give records an order that does not clash with heapq. Decorated tuples: push (priority, n, record), where n counts pushes so the tuples never tie and the record is never compared. Objects with their own __lt__: a Job holding priority, n and record, whose __lt__ compares (self.priority, self.n) with (other.priority, other.n). Both pop the smallest priority first and break ties by arrival.

  1. Build both on 3 * 10^4 jobs with seeded priorities from 0 to 99 (many ties), push all of them, pop all of them, and assert the same pop order, equal to sorted by (priority, n).
  2. In a counted copy of Job, count __lt__ calls per push and per pop during the same script. Print the averages, and assert each stays within its bound: a push does at most log2(n) comparisons, a pop at most 2 * log2(n).
  3. Time both on plain code (min of 3) and print the ratio of the Job time to the tuple time, with no verdict.
  4. When would you still write __lt__? When the order is not a tuple of fields. The reversed wrapper earlier in this topic made any item sort backwards; here the same idea: records ordered by name descending and by arrival ascending, which no tuple can express for strings (they cannot be negated). Pop 12 such records and assert they match two stable sorts.
Q66The Skyline With A Heap Of HeightsHard

Buildings are (left, right, height) with integers left < right and height >= 1. The skyline is the list of (x, height) points where the outline's height changes, in order of x, ending with a point of height 0 where the last building ends; the height before the first point is 0, and no two neighbouring points have the same height. Sweep the x values that are an edge of some building, from left to right, with a max-heap of (-height, right) for the buildings that have started. At each x: apply every edge at that x first (push all buildings with left <= x), drop the tops with right <= x (lazy: a building that ended below the top stays in the heap and does not matter), and only then read the height (the top, or 0 for an empty heap). If it differs from the previous point's height, record (x, height).

  1. Write skyline(buildings) and skyline_scan(buildings), the brute force: for each edge x, the height is the largest height among buildings with left <= x < right, and the points are the changes. Check them equal on 300 seeded inputs (empty, one building, nested buildings, equal edges and a building that ends where another of the same height starts). Count the inputs of each kind and catch every Exception as a failure.
  2. Print the skyline of [(2, 9, 10), (3, 7, 15), (5, 12, 12), (15, 20, 10), (19, 24, 8)].
  3. skyline_ends_first is the broken version: at each x it handles the ending buildings and records the height before it adds the buildings that start there. Find by a plain search the smallest failing input and print it beside the truth.
Q67The Best Team With A Shared MinimumHard

Each engineer is (speed, efficiency), both at least 1. A team of at most k engineers (k >= 1, ValueError otherwise) scores sum of the speeds * the smallest efficiency in the team. Find the best score (0 when there are no engineers). The idea: try every engineer as the team's least efficient member. Go through the engineers in descending efficiency; everyone seen before has at least this efficiency, so the best partners for the current engineer are the k - 1 fastest engineers seen before. Keep those in a min-heap of speeds of size at most k - 1 with a running sum, so each candidate costs O(log k): score the candidate as (sum + speed) * efficiency, then push the speed and, if the heap now holds more than k - 1, pop the smallest speed and subtract it from the sum.

This enumerates every choice of the least efficient member; it is not a proof that picking the fastest partners is always right, and that kind of argument is DSA Topic 20. The check below is a brute force over every team.

  1. Write best_team(engineers, k) and best_team_scan(engineers, k), which tries every team of size 1 to min(k, n) with itertools.combinations.
  2. Check them equal on 400 seeded inputs (empty, one engineer, k = 1, k >= n, equal efficiencies and equal speeds). Count the inputs of each kind, catch every Exception as a failure, and print the mismatches.
  3. Print a small example with its best score.
Q68Starvation And AgingHard

A scheduler serves one job per tick and always takes the highest-priority waiting job (priority 0 is high, 1 is low; ties by arrival order). Under a heavy stream of high-priority jobs a low-priority job can wait for ever: it starves. Aging fixes that: a job's effective priority falls by 1 for every c ticks it has waited, continuously, so at tick t a job that arrived at tick a has effective priority priority - (t - a) / c.

Aging needs no update of the jobs already in the heap. Multiply by c: the effective priority is priority * c - t + a, all over c. The - t is the same for every waiting job at tick t, so it never changes who is smallest. The order is therefore exactly the order of the static key priority * c + a, with ties broken by arrival number n.

  1. Build 20,000 ticks of arrivals with a seeded generator: each tick a high job arrives with probability 0.99 and a low job with probability 0.02 (the high one first). Simulate three policies on the same arrivals: no aging (key (priority, n)), c = 10 and c = 100 (key (priority * c + a, n)). Each tick, add the arrivals, then serve the smallest key. Print, for each policy: the longest wait of a served low job (ticks from arrival to service), the low jobs still waiting at the end, and the longest wait of a served high job.
  2. Check the static key against simulate_scan, a brute force that recomputes every waiting job's effective priority priority * c - (t - a) each tick and scans for the smallest, on 200 seeded short runs (300 ticks, high 0.9 to 0.99, low 0.05 to 0.3) for c in 1, 3, 10 and 100, and for no aging. Compare the full service order, count the runs where aging changed the order, and catch every Exception as a failure.
  3. Close with a sentence built from the printed numbers.
Q69The Bottom-Up Pop heapq UsesMedium

The textbook pop puts the last item at the root and sifts it down, comparing it with the smaller child at every level: two comparisons per level (one between the children, one against the item). The bottom-up pop does less. Remove the root and the last item; treat the root as a hole. Move the hole down to a leaf by moving the smaller child up into it at every level (one comparison per level, between the two children). Then put the last item in the hole and sift it up (usually a step or two, because the last item came from the bottom and is usually large). CPython's heapq.heappop does this too (a hole down to a leaf, then a sift up); its private helpers are named the other way round to this topic (_siftup moves the hole down), so never call them.

Key (a wrapper whose every < adds 1 to Key.compares), is_heap, heapify, random_list, the hand-written MinHeap (whose pop is the textbook pop) and the lists BED are written out in the answer.

  1. Write pop_bottom_up(a): in place on the list a (a min-heap), returning the smallest item, IndexError on an empty list. Check on every list in BED (heapified first) that popping everything gives sorted order and that a is a heap after every pop. Count the lists of each kind (empty, single, sorted, reverse-sorted, all equal, with duplicates) and assert each count is above 0.
  2. On a heap of 10^5 distinct Keys (a shuffled range(10**5)), count the comparisons of each of the first 2 * 10^4 pops for the textbook MinHeap.pop, pop_bottom_up and heapq.heappop (heappop is C code that calls Key.__lt__, so its real comparisons are counted), and print the averages beside 2 * log2(n). Assert the three pop the same values, that each average is at most 2 * floor(log2 n), and that pop_bottom_up and heappop make the same number of comparisons on every single pop. (With equal children CPython moves the right child up and this code moves the left, so on keys with ties the per-pop counts can differ; distinct keys avoid that.)
  3. pop_bottom_up_no_sift_up is the broken version: it leaves out the final sift up. Find by a plain search over BED (shortest first, heaps only) the smallest failing heap and print it beside the truth.
  4. Close from the counts: say whether bottom-up used fewer comparisons than the textbook pop and whether heappop matched it on every pop.
Q70Heap, Sorted List Or BST, MeasuredHardMust Do

Which structure should hold a priority queue (numbers in, the smallest out)? Measure three, and decide from the printed numbers. Each offers push(x) (add a number; duplicates allowed) and pop() (remove and return the smallest; IndexError when empty):

  • HeapPQ: heapq on a list (heappush, heappop).
  • SortedPQ: a sorted list that stores the negated numbers in ascending order, so the smallest number is at the end; push is bisect.insort(items, -x) (a binary search, then a shift of the tail: O(n) but one fast C-level memory move) and pop is items.pop() from the end, followed by negating. DSA Topic 14 already measured a sorted list against a search tree on a changing set of keys with rank queries; here the heap joins in.
  • TreePQ: a plain binary search tree (no balancing; smaller keys left, equal or larger keys right), with iterative code. push walks down from the root to a free place; pop walks left from the root to the smallest node and cuts it out by letting its parent take its right child (or the root become that child). Its height counts the levels, by a level-by-level sweep. DSA Topic 14 showed that sorted inserts build a path and that nearly sorted inserts are nearly as bad.

Key (a wrapper whose every < between two Keys adds 1 to Key.compares; used only to count) and these classes are written out in the answer. Four workloads, each with 2 * 10^4 operations (N), all built from seeded data before timing; every run starts from an empty structure and builds the initial items by pushes, which is part of its time:

  • hold, m = N / 10: m items start in the structure (random in range(1000)); then N times: pop the smallest and push it back plus a random increment from 1 to 999 (what an event queue does with a clock).
  • hold, m = N: the same with m = N items held.
  • mixed: N operations, each a push of a random number (probability 1/2) or, if the structure is not empty, a pop.
  • fill, then drain: N / 2 pushes of random numbers, then N / 2 pops.
  1. Check that all three return the same popped numbers on every workload (a separate traced run that records the pops), and print the number of pops compared.
  2. Time every structure on every workload (plain code, min of 3) and print the times and the ratios SortedPQ / HeapPQ and TreePQ / HeapPQ. Every ratio is printed as a ratio only: a time ratio moves with the machine's load, so no verdict rests on one.
  3. The hold verdicts come from counts, which do not move with the load. In separate counted copies, count the nodes the tree visits per hold operation and the comparisons heapq makes per hold operation (with Key) for both hold workloads, check the counted tree ends at the same height as the plain one, and print "more work per operation" for the tree only if its count is at least 2x the heap's.
  4. After the hold workload with m = N / 10, print TreePQ.height() beside the height of a tree built by pushing the same final keys in shuffled order, and print how many hold pushes were larger than every number held at that moment. Say why from the data: the smallest number keeps rising, so later pushes are larger on average and the inserts arrive nearly sorted; assert the hold tree is taller than the shuffled one.
  5. Show what the heap cannot answer: on a heap of 1,000 random numbers, the k-th smallest (k = 500) is one index read on the sorted list but k pops on the heap (count them), and a count of numbers in a range needs a scan of the heap but two binary searches on the sorted list (assert the two counts are equal, and that the heap's array is not in order).
  6. Close with a decision built from the verdict variables, never typed: the verdict against the plain tree, what the sorted list's ratios were (no verdict), and when a sorted list or a tree is the better choice. sortedcontainers (a third-party library that keeps a sorted list fast as it grows) is named here and never imported.
Q71Off-By-One In Parent And ChildMediumMust Do

A min-heap here is a 0-based Python list a read as a complete binary tree in level-order, in which no item is smaller than its parent, so a[0] is the smallest. The parent of slot i (for i >= 1) is (i - 1) // 2 and its children are 2i + 1 and 2i + 2. Items are compared with < only. Push appends an item and sifts it up (swap it with its parent while it is smaller). Pop saves a[0], moves the last item into slot 0 and sifts it down (swap it with its smaller child while that child is smaller); an empty heap raises IndexError. Heapify rearranges a list in place by sifting down every slot that has a child, last one first.

These index formulas are where hand-written heaps break. These helpers are written out in the answer: is_heap(a) is True when no item is smaller than its parent; sift_up(a, i) and sift_down(a, i, n) are the two correct moves (sift_down works inside a[0:n]); random_list(n, rng, span) returns exactly n random ints below span; and BED holds 9,194 small lists, every order of 0..k-1 and every list over 0, 1, 2, each of length 0 to 7.

Here are four believable bugs, each one changing a single formula:

  • B71a uses the 1-based children 2i and 2i + 1 in sift down.
  • B71b uses the 1-based parent i // 2 in sift up.
  • B71c tests the right child with child + 1 <= n, so it can read one slot past the heap.
  • B71d loops while i >= 0 in sift up, so slot 0 is compared with slot (0 - 1) // 2 = -1, which is the last item.
  1. For each bug, find its smallest failing list by scanning BED from the shortest list (orders before lists with repeats at each length). On each list, push the items one at a time, pop everything, and heapify a copy, then pop that copy. Check is_heap after every one of these operations. A list fails if any check is False, if the pops come out unsorted, or if anything raises. Print what broke beside what the correct formulas give.
  2. Run the same check on all of BED and sort every failure into "raised", "caught by is_heap" or "seen only in the pop order". Assert that the last group is empty for every bug.
  3. Show why the property check matters. With B71b, count the lists of BED whose pops come out unsorted, then the same over 300 random lists of 100 items.
  4. Fuzz the correct formulas against sorted() on 300 seeded lists: empty, a single item, sorted, reverse-sorted, many duplicates and random. Count each kind, count every Exception as a failure, and check that popping an empty heap raises IndexError. End with the lesson, printed only if the counts support it.
Q72Sift-Down BugsHard

Two student versions of sift_down(a, i, n) look almost right:

  • B72a swaps a[i] with its smaller child but never moves i down to the child, so the item sinks one level and stops.
  • B72b breaks out of the loop unless both children exist (if child + 1 >= n: break), so a slot with only a left child is never compared with it.

A pop moves the last item into slot 0 and sifts it down, so either bug shows up as a pop that leaves a bad heap.

  1. Predict from the code alone the size of the smallest heap on which a pop goes wrong for each bug, and print each prediction with its reason.
  2. Confirm the predictions by scanning the heaps of BED from the shortest (the 9,194 lists of every order of 0..k-1 and every list over 0, 1, 2, lengths 0 to 7, keeping those that pass is_heap). Pop everything from each heap and report two things per bug: the first heap whose pops leave an array that fails is_heap, and the first heap whose pops come out unsorted, beside the truth. Assert that the first matches your prediction.
  3. Write a fuzz of 300 seeded push and pop scripts against a plain list scanned for its minimum. The scripts cover empty, single-item, sorted, reverse-sorted, duplicate-heavy and random inputs, and each ends with a pop on an empty heap that must raise IndexError. Count any Exception as a failure. Run it on both bugs (each must fail some scripts) and on the correct sift_down (no failures, every kind counted).
Q73Heapify Loops That Stop EarlyMedium

Heapify sifts down every slot that has a child, from slot n // 2 - 1 back to slot 0, each within the whole heap a[0:n]. Two loops stop one step short:

  • B73a: for i in range(n // 2 - 1, 0, -1) never reaches slot 0, so the root is never sifted.
  • B73b: sift_down(a, i, n - 1) passes the wrong size, so the last slot is never compared.
  1. Find each one's smallest failing list in BED (every order of 0..k-1 and every list over 0, 1, 2, lengths 0 to 7, shortest first). A list fails when the result is not a heap of the same items. Print each result beside the correct heapify. Show that both bugs fail first on the same input, for two different reasons.
  2. A failing input that both bugs share cannot tell them apart. Scan BED for the first list that fails only B73a and the first that fails only B73b, and print what each bug leaves on both lists. Then count how many lists of BED each bug fails, and how many both fail.
  3. Check the correct heapify on all of BED, then fuzz it on 300 seeded lists against sorted(): empty, single, sorted, reverse-sorted, duplicate-heavy and random lists of up to 300 items. Assert that each result is a heap, pop it to the end, and count every Exception as a failure.
Q74Changing An Item In PlaceEasy

A Task has a priority (smaller runs first) and a unique name that breaks ties, and it compares by (priority, name) in __lt__. Tasks sit in a heapq list. B74 is the shortcut task.priority = new on a task that is still inside the heap. The heap never hears about the change.

  1. Find the smallest case by a plain search. Heapify tasks whose priorities come from each list of BED (shortest first), then change one slot to every new priority from -1 to n, and stop at the first case where the next heappop differs from a scan for the smallest (priority, name). Print the heap, is_heap after the edit, the wrong pop and the right one. Then write reprioritise(h, task, new), which takes the task out of the heap (found by identity), restores the heap, changes the priority and pushes the task again. Show that it gets the same case right.
  2. Count over every heap of BED, every slot and every new value from -1 to n how often the edit in place leaves a non-heap and how often the next pop is wrong.
  3. Fuzz reprioritise against a list scan with 300 seeded scripts of pushes, priority changes and pops. Cover empty, single, sorted, reverse-sorted, duplicate and random priorities, end each script with a pop on the empty heap (which must raise IndexError), and count any Exception as a failure.

reprioritise costs O(n). Two cheaper fixes appear earlier in this topic: re-push the task and skip the stale entry when it is popped, or keep an index map so the slot is known in O(1) and one sift fixes it. DSA Topic 7's mutable key and DSA Topic 14's key changed after insert make the same mistake in a hash table and a search tree.

Q75Counters That Are Not UniqueHard

A stable priority queue stores (priority, n, item) with n a tie-breaker. Equal priorities then leave in arrival order (FIFO) and Python never compares two items. That only works if n never repeats. Two student versions repeat it:

  • B75a uses len(self.h) as the tie-breaker. It falls after a pop, so a later push can reuse a number.
  • B75b creates count() inside push, so every entry gets 0.

The oracle is a plain list. Its pop scans for the smallest priority and takes the first one found, comparing priorities only.

  1. Run every script of 1 to 6 operations (push with priority 0, push with priority 1, or pop), then drain the queue, using string items. Name them once in ascending order of arrival ("joba", "jobb", ...) and once in descending order ("jobz", "joby", ...). Count the errors and the scripts that break FIFO for each bug and each naming. Strings compare quietly, so nothing raises: the test with ascending names hides most of the damage. Print each bug's smallest script that breaks FIFO, beside the oracle.
  2. Repeat with dict items. Print each bug's smallest failing script with the TypeError and the operation that raised it, and print the error message once. The stable priority queue from earlier in this topic showed the same error with no counter at all.
  3. The fix is one itertools.count() per queue, made in __init__. Fuzz that queue against the oracle on 300 seeded scripts with dict items: empty, single, sorted, reverse-sorted, duplicate and random priorities, pops mixed in, and an extra pop at the end that sometimes hits an empty queue. Count each kind and every Exception as a failure.
Q76nan And Mixed Types In A HeapMedium

A heap needs a total order: for any two items, exactly one of x < y, y < x or "equal" holds. float("nan") breaks that, because every comparison with it is False. Types that cannot be compared break it too.

  1. Print nan < 1.0, 1.0 < nan and nan == nan.
  2. Scan every list of 0 to 6 items over 0.0, 1.0, 2.0, nan (shortest first) for the smallest list each way of building gets wrong: the hand-written heapify then pops, heapq.heapify then pops, and heappush one at a time then pops. Judge only the order of the numbers among the pops, leaving nan out. Print each list, its pops and the numbers sorted, then count how many of the lists holding a nan come out wrong. Nothing raises an error.
  3. Push the str "three" onto the heap [3], catch the TypeError and print its type and message. Two strs compare fine.
  4. Fix it at the door with CheckedHeap. Its push refuses nan with ValueError and refuses any key whose type differs from the first one pushed with TypeError, and both happen before any comparison. Fuzz it on 300 seeded float lists against sorted() of the accepted items: empty, single, sorted, reverse-sorted, duplicates and random, with nan and int pushes mixed in that must be refused. Count the refusals and every Exception as a failure, and check that an empty pop raises IndexError.

DSA Topic 14 met the same keys that break the order in a search tree.

Q77Two-Heap Medians That DriftHard

The running lower median (the item at index (n - 1) // 2 of the n items sorted) can be kept with two heapq heaps. low is a max-heap of the smaller half, stored negated, and high is a min-heap of the larger half. Three rules must hold after every add:

  • the sizes: len(low) is len(high) or len(high) + 1;
  • the tops: low's top is no larger than high's top;
  • the items: the two halves, decoded, hold exactly the items added.

Two bugs make the median drift:

  • B77a pushes every item to low and moves a top to high only when the sizes are off. Nothing ever compares the two tops.
  • B77b moves high's top to low without negating it.
  1. For each bug, find the smallest stream in BED (shortest first) where its medians differ from a sorted list kept with insort. Print both lists and the first rule broken, with the add that broke it.
  2. Run every list of BED as a stream through both bugs and the correct version, checking the three rules after every add. Assert that whenever the medians go wrong, a rule broke at or before the first wrong median, and count which rule broke first. On BED's non-negative items, a check of the sizes and the tops alone never catches B77b first: assert it. Then search the lists of up to 5 items over -2, -1, 0 and 1 (shortest first) for the smallest stream where the tops rule does catch B77b first, and print it.
  3. Fuzz the correct version on 300 seeded streams against insort: empty, single, sorted, reverse-sorted, duplicate and random. Check the three rules after every add and count every Exception as a failure.

This differs from the one-way rebalance earlier in this topic, which moved items only from low to high: these two bugs move items correctly in both directions, but one never compares the tops and the other stores a top without negating it. DSA Topic 5 kept a sliding median in a sorted list with bisect, the same method as the oracle here.

Q78Top-k BugsMedium

The contract of top_k(items, k): return the k largest items, largest first. k <= 0 gives [] and k >= n gives every item. Items may be any iterable, read once. It keeps a min-heap of at most k items, and a new item replaces the top only when it is larger. Two bugs:

  • B78a replaces the top for every new item once the heap is full, larger or not.
  • B78b has no guard for k <= 0, so with an empty heap the "full" branch reads h[0].
  1. For every list of BED (shortest first) and every k from -1 to n + 1, compare each bug with sorted(items, reverse=True)[:max(k, 0)], counting a raised exception as a wrong answer. Print each bug's smallest failing input beside the truth, and how many of the cases it gets wrong.
  2. Check the correct top_k on the same cases. Then fuzz it on 300 seeded lists (empty, single, sorted, reverse-sorted, duplicates, random) with k in -1, 0, 1, a random value, n and n + 1, passing an iterator so it is read only once. Count every Exception as a failure.
Q79k-Way Merges That Lose ItemsMedium

merge_k(lists) merges sorted lists with a heap of (value, list index, position) entries. It skips empty inputs, pops the smallest entry, and pushes the next item from the list that entry came from. Two bugs:

  • B79a runs only "while every list still has items". It stops as soon as any input runs out, and it reads lst[0] of every input, empty ones included.
  • B79b takes the next item from lists[0], not from lists[i].
  1. Build every input of up to 3 lists, each a sorted list of up to 2 items from 0 and 1, ordered by the number of lists and then the number of items. For each bug, print the smallest input where it differs from sorted(chain(*lists)), with an exception counted as a difference. If that first failure is an exception, also print the smallest input where it quietly loses items. Then count its wrong answers. Print what B79a does with two empty inputs.
  2. Check merge_k on every small input, then on 300 seeded ones: no lists, all empty, a single item, ascending blocks (list 0 holds the smallest values), descending blocks (list 0 the largest), duplicates and random. Count each kind and every Exception as a failure.
Q80Index Maps That Go StaleHard

The indexed heap from earlier in this topic keeps (priority, item) entries in a list a and a dict pos from item to slot, so update(item, priority) finds its slot in O(1) and sifts it up or down. Items are unique, and ties go to the smaller item. Its alternative, lazy re-push, pushes a new entry on every change and skips stale entries when they are popped. Each has a way to go stale:

  • B80a: the swap helper moves two entries but writes pos for only one of them.
  • B80b: the lazy pop skips an entry only if its item was already popped, never because the entry is out of date. The right test is whether the entry's priority is the item's current one.

The oracle is a dict from item to priority, popped by scanning for the smallest (priority, item).

  1. Run B80a on every valid script of 1 to 4 operations over items a, b and priorities 0 to 2 (push, update, pop), fewest operations first. After every operation, check is_heap, that pos matches every slot, and that the entries equal the oracle's. Print the smallest script that breaks a rule and the array it leaves. Then turn the pos check off and print the smallest script whose damage shows anyway. That array still passes is_heap.
  2. Run B80b on every script of 1 to 5 operations (set or pop). Each popped pair must be the oracle's, so its priority must be the item's current one. Print the smallest failing script with the broken pops and the true ones.
  3. Run 300 seeded scripts through each of the four versions with the same checks after every operation. Cover empty, single, sorted, reverse-sorted, duplicate and random priorities, mix in updates and pops, and end with pops on the empty queue, which must raise IndexError. Count every Exception as a failure. The two bugs must fail some scripts and the two correct versions none.
Q81Accidentally Quadratic HeapsHardMust Do

A min-heap here is a Python list a read as a complete binary tree in level order: slot i has parent (i - 1) // 2 and children 2 * i + 1 and 2 * i + 2, and no item is smaller than its parent, so a[0] is the smallest. push(x) must add x and keep that rule, and pop() must return the smallest item and keep it. A correct heap does each in O(log n), so n pushes and n pops cost O(n log n).

Code can be accidentally quadratic: correct on every test, yet O(n^2) over n operations, so the first big input stalls it. Two ways to get there with a heap:

  • B81a calls heapify over the whole list after every append, "to be safe". It is correct, but each call costs O(m) for the m items held, and it runs once per push.
  • B81b never builds a heap: it keeps a plain list, appends on push, and pops with min() followed by remove(). Each pop scans the whole list with min(), then again with remove() up to the match; only min()'s comparisons are counted.

These helpers are written out in the answer: Key (wraps a value so every < between two Key objects adds 1 to Key.compares: it is how a comparison is counted, and it is used for counting only, never for timing), sift_up and sift_down (swap an item with its parent while it is smaller, or with its smaller child while that child is smaller), heapify (rearranges a list in place into a heap, bottom-up, in O(n) for n items), MinHeap (the correct heap, built on them) and best_of (the smallest time of 3 runs).

  1. Write the correct version and both slow ones, each as "push every item of a list, then pop them all, and return the pops". Check all three against sorted() on an empty list, one item, sorted, reverse-sorted, all-equal and seeded random lists. Count the cases each kind hit and count any Exception as a failure. This shows that nothing but the cost is wrong.
  2. Find, by a plain search over n = 1, 2, 3, ..., the smallest n (on a seeded random permutation of n items) at which each slow version makes at least twice as many comparisons as the correct one.
  3. Count comparisons at n = 100, 200, 400 and 800 and print the growth each time n doubles. Decide from the counts alone: a growth of at least 3.5 per doubling means quadratic, at most 2.5 means about n log n. Assert the verdicts.
  4. Time the plain code (never the counted copy) with best_of, B81a at n = 800 and B81b at n = 3,000, each beside the correct heap at the same n, and print the slow-to-correct time ratios. The ratios are printed only: the verdict comes from the counts.
  5. Print a closing line built from the verdicts.
Q82Schedulers That Run The FutureMedium

Earlier in this topic a scheduler simulated one worker. Jobs are (id, arrival, length, priority) with integer times and length >= 1. The rule: whenever the worker is free it starts the waiting job with the smallest priority number, ties broken by the earlier arrival and then by the smaller id; a job runs to its end; and when nothing is waiting the worker waits for the next arrival, so the clock jumps there. A job is waiting only once its arrival time has come (arrival <= clock). The result is the list of runs (id, start, finish) in the order they ran. The rule is simulated here, not proved best: whether any rule is the best possible is greedy algorithms, DSA Topic 20.

The correct scheduler feeds a heapq heap of (priority, arrival, id, length) from the jobs sorted by (arrival, id), admitting every job that has arrived by the clock. The brute force scans every job still to run, picks the waiting one with the smallest (priority, arrival, id) and removes it. Two student bugs run the future:

  • B82a pushes every job into the heap at time 0, so a job can start before it has arrived.
  • B82b handles the idle case on its own: when nothing is waiting it jumps to the next arrival, but pushes only that one job and not every job that has arrived by then (jobs that arrive meanwhile are admitted after the run).
  1. Write the correct scheduler, the brute force and both bugs.
  2. Enumerate every job list of up to 3 jobs whose arrival is in {0, 2}, length in {1, 3} and priority in {0, 1} (ids are the positions): 585 lists. Check the correct scheduler against the brute force on all of them.
  3. For each bug find, by a plain scan of those lists in order of size, the first list on which it differs from the brute force, and print its runs beside the truth. Assert that it fails there.
  4. Fuzz the correct scheduler against the brute force: an empty list, one job, arrivals in order, arrivals in reverse order, all jobs arriving together, all priorities equal, and 300 seeded random lists. Count the cases that had simultaneous arrivals, an idle gap and equal priorities, and count any Exception as a failure.
Q83heapq's Silent TrapsEasy

heapq keeps a min-heap in a plain list (the smallest item at index 0, each item at least as large as its parent) and gives you functions that change that list. It has no heap class, so three habits that are fine with other Python types fail silently or late:

  • B83a: h = heapq.heapify(xs). heapify works in place and returns None, as list.sort() does, so h is None.
  • B83b: heapq.heappush(xs, x) on a list that was never heapified. heappush assumes its list already obeys the heap rule; on a list that does not, it keeps a broken array without an error, and the smallest item is no longer at index 0.
  • B83c: comparing two heaps with ==. A heap is a list, but the same items can be laid out in more than one valid way (heapify and pushing one at a time can disagree), so two correct heaps of the same items can be unequal lists. Compare the pop order, or sorted() of each.
  1. For each bug write the broken line and the right way.
  2. Find each bug's smallest failing input by a plain scan, in order of size: for B83a every list over 0, 1, 2 of length 0 to 3, for B83b every such list of length 0 to 4 with every pushed value in 0, 1, 2, and for B83c every order of 0..k-1 for k = 0 to 5. Print the failure beside the truth and assert it.
  3. Write the right versions, then fuzz them: an empty list, one item, sorted, reverse-sorted, all-equal and seeded random lists with many duplicates. Check that the built heap pops in sorted() order, that pushing one more value and popping gives the minimum, and that both ways of building a heap give equal pop orders. Count the cases of each kind and count any Exception as a failure.
Q84The Recursion That Cannot Run OutEasy

A recursive function runs out of frames when its depth grows with the input. DSA Topic 14's recursion on a search tree built from sorted keys did exactly that: that tree is as tall as the input has keys, so one call per level meant one call per key. A heap cannot do this, because it is a complete binary tree (every level full except the last, which fills from the left): n items always have n.bit_length() levels, which is floor(log2 n) + 1. A recursive sift_down makes one call per level it descends, so it is safe on any heap of any order.

sift_down(a, i, n) moves a[i] down inside the heap a[0:n]: it swaps with the smaller child while that child is smaller. heapify rearranges a list in place into a heap by sifting down every slot that has a child, last slot first.

  1. Write sift_down_rec with a depth argument that counts its frames (the first call is depth 1) and records the deepest and the swaps in a small dict, and write the same walk as a loop, sift_down_loop, which returns its swaps.
  2. Build a heap of 100,000 random items with the recursive heapify and pop every item with the recursive sift_down. Print the deepest depth against n.bit_length() and against sys.getrecursionlimit() (as a boolean: is the deepest depth under the limit?). Assert the deepest depth is at most n.bit_length(). Never print a depth at which a recursion failed, and never change the limit.
  3. Print what 1,000,000 items would need, computed from bit_length and not run, and what a path as tall as the input would need beside the limit, as a boolean.
  4. On 20,000 random items, run both versions through heapify and through a full pop-all. They must make the same swaps (counted, asserted) and leave the same arrays.
  5. Fuzz the recursive version against sorted(): an empty list, one item, sorted, reverse-sorted, all-equal and seeded lists with many duplicates, each counted, with any Exception counted as a failure.
Q85The Suite For Any Priority QueueHardMust Do

A test suite is itself a program, and it needs testing: a suite that passes a correct queue proves little until you have seen it fail a broken one. Write one suite for any stable priority queue with cancelling, then run it on three correct implementations and on six planted bugs.

The contract of a queue q (the suite never pushes an item that is already live, so that case is outside the contract):

  • q.push(priority, item) adds a live entry. A smaller priority leaves first; equal priorities leave in the order they were pushed (FIFO). Items are hashable and never compared.
  • q.pop() removes and returns (priority, item) of the live entry that leaves first. IndexError when there is no live entry.
  • q.peek() returns the same pair without removing it. IndexError when there is no live entry.
  • len(q) is the number of live entries.
  • q.cancel(item) makes the item's live entry never served and returns True; it returns False if the item has no live entry (never pushed, already popped or already cancelled). A later push of the same item is a new entry: it is served normally.
  • item in q is True exactly when the item has a live entry.

A script is a list of operations ("push", item, priority), ("pop",) and ("cancel", item). The reference queue RefPQ is the brute force: a scan-for-the-smallest list (ListPQ) of (priority, n, item) entries, where n counts pushes, and cancel removes the entry from that list for real.

These helpers are written out in the answer: sift_up and sift_down (swap an item with its parent while it is smaller, or with its smaller child while that child is smaller), MinHeap (a binary min-heap in a list, built on them), ListPQ (an unsorted list whose pop scans for the smallest item and removes the first one found), StablePQ (a queue of (priority, n, item) entries on MinHeap, n from itertools.count()), and PQ (the same on heapq). Cancelling(base) turns any of them into the contract above by marking: it keeps a dict live from each live item to the push number of its live entry, and an entry that reaches the front is skipped when its push number is not the one in live.

  1. Write the suite as a list of named tests, each a script plus the observations to check after every operation (len, peek, in). It runs the subject and RefPQ side by side and compares every result and observation. The first nine tests are small and aimed: an empty queue's peek, an empty pop, len after a pop, a priority beating the item's name, a tie, a cancelled entry never served, a re-pushed item, in, and priorities that rise, fall or are all equal. Then one test runs every script of up to 4 operations over items a, b and priorities 0, 1 (2,801 scripts), and one runs 300 seeded scripts over three items. These two run each script twice, once observing everything and once observing nothing, because an observation is not free of side effects: peek on a marking queue drops stale entries, which can hide a bug that a run without observations would show. A test that raises any Exception is a failure, not a crash; it names the exception.
  2. Run the reference and count how often the tests hit an empty pop, an empty peek, a tie served, a successful cancel, a cancel that returned False and a re-push of an item that was served or cancelled. Assert each was hit.
  3. Run the suite on the three correct queues (the hand-written heap, heapq through PQ, and the scan through ListPQ) and assert that every test passes.
  4. Run it on six planted bugs: S1 peek on an empty queue returns None; S2 len is not reduced by pop; S3 entries are ordered (item, priority, n); S4 cancel marks the item's name, so a re-pushed item is lost; S5 pop does not skip cancelled entries; S6 in is written item in self.base.h (the heap list holds tuples, so it is always False).
  5. Print which test caught which bug (the first failing test), assert that it is the aimed test, and for each bug also print the smallest script the exhaustive test found.
Q86The Updatable Priority QueueMini-ProjectMust Do

A job queue, an event queue or a scheduler needs more than push and pop: a job's priority changes while it waits, and a job is withdrawn. heapq keeps no map from an item to its slot, so it cannot change or remove an item in O(log n). Earlier in this topic a dict pos from each item to its slot, kept right by one swap helper, made decrease-key O(log n). Here that design grows into a complete class.

The class differs from that earlier heap on purpose: its entries are (priority, seq, item), and it adds remove and a repair step _fix. Build UpdatablePQ, a binary min-heap in a list a (slot i has parent (i - 1) // 2 and children 2 * i + 1, 2 * i + 2) of entries (priority, seq, item), with a dict pos from each held item to its slot. seq is a number from an arrival counter, so two entries never tie and items are never compared: they only need to be hashable. Priorities are numbers; a smaller priority is served first. The contract:

  • push(item, priority): add the item with the next seq. ValueError if the item is already held.
  • pop(): remove and return (item, priority) with the smallest priority, and among equal priorities the one pushed earliest (smallest seq). IndexError when the queue is empty.
  • peek(): the same pair, left in place. IndexError when empty.
  • update(item, priority): give the held item a new priority, smaller or larger. The entry keeps its seq, so among equal priorities it keeps its place in line (updating an item to the priority it already has changes nothing). KeyError if the item is not held, including an item that was popped or removed.
  • remove(item): take the item out and return the priority it had. KeyError if it is not held.
  • item in pq is True exactly when the item is held, and len(pq) is the number held (__contains__ and __len__).
  • Every operation is O(log n) except that peek, len and in are O(1). Every move of an entry goes through one helper _swap(i, j), which exchanges two slots and writes both new positions into pos; nothing else writes pos except push (a new entry) and the removal (a deleted entry).

These helpers are written out in the answer: is_heap (true when no entry is smaller than its parent), ModelPQ (a dict from item to (priority, seq) whose pop finds the minimum by scanning: the brute force), and outcome (runs a call and returns its result, or the name of an exception the contract names), and Token (an item that is hashable and has no <).

  1. Write UpdatablePQ and check the contract on a short trace, including three items with equal priorities and a Token class (hashable, with no <) to show that items are never compared.
  2. Check it against ModelPQ on 500 seeded scripts of pushes, pops, peeks, updates and removals, plus an empty script, a one-operation script, and ascending, descending and all-equal priorities. After every operation compare the result (or the exception type) with the model's, and assert that pos[a[i][2]] == i for every slot, that len(pos) == len(a), that is_heap(a) holds and that the held items and their (priority, seq) match the model. Count how many times each case was hit (empty pop, empty peek, duplicate push, update or remove of a missing key, update or remove of an item that was removed, ties served, updates that keep a place), and count any Exception as a failure.
  3. Print one line citing the earlier measurement of the index map against lazy re-push: about equal in time, while lazy re-push holds n + u entries when the u updates come before any pop. This class is not repeated against it.
Q87The Timer ServiceMini-Project

A timer service holds timers that fire later: a session expiry, a retry, a reminder. A heap keyed by due time finds the next timer to fire in O(1) and removes it in O(log n). Cancelling is the awkward part: removing an entry from the middle of a heapq list is a search and a repair, so the service marks the timer cancelled and leaves its entry where it is (the same recipe as cancelling a job earlier in this topic). An earlier question already wrote a compact() that rebuilds the heap from the live entries and heapifies it; the new part here is the program's rule for when to call it. Marked entries are stale: they cost memory and are skipped when they reach the front, so a service that cancels most of what it schedules would keep growing. The fix is an explicit compact().

Build TimerService on heapq. Times are integers. The service has a clock now, which starts at 0 and never goes back. The contract:

  • schedule(delay, name): a timer due at now + delay. Returns its timer id: 0 for the first call, then 1, 2, and so on. ValueError if delay < 0. A timer with delay == 0 is due now and fires on the next advance.
  • cancel(timer_id): returns True if the timer is pending (scheduled, not yet fired, not cancelled) and cancels it; False otherwise (already fired, already cancelled or never issued).
  • advance(new_now): moves the clock to new_now and fires every pending timer with due <= new_now, in (due time, id) order. Returns the list of their names. ValueError if new_now < now.
  • next_due(): the due time of the earliest pending timer, or None if there is none.
  • compact(): rebuilds the heap without the stale (cancelled) entries and returns how many it removed. The service never calls it by itself.
  • pending() is the number of pending timers and heap_size() the number of entries in the heap, stale ones included.

The program's rule (a driver outside the class): after every cancel, if the stale entries (heap_size() - pending()) outnumber the pending timers, call compact() and record the heap size before and after.

These helpers are written out in the answer: TimerList (the brute force: a plain list of [due, id, name, state] records, whose advance scans all of them and sorts the due ones) and outcome (runs a call and returns its result, or the name of an exception the contract names).

  1. Write TimerService, TimerList and the driver.
  2. Run one seeded workload and print every compaction: the heap size before and after. After a compaction the heap size must equal pending().
  3. Check the service against TimerList on 300 seeded scripts, comparing every return value (or exception name) and pending(), plus an empty script, a script of one timer, delays that ascend, delays that descend and all-equal delays. Count the cases hit (an advance that fires nothing, several timers fired by one advance with equal due times, a cancel that returned False for each of its three reasons, ValueErrors, compactions) and count any Exception as a failure.
Q88The Live LeaderboardMini-Project

A game keeps a score for every player. add(name, points) gives a player points more (a whole number of at least 1; ValueError otherwise, so a new player starts at 0), and top(k) returns the k best players as a list of (name, score), highest score first, equal scores by name (alphabetical). top(0) and a negative k give [], and a k larger than the number of players gives every player. A board with no players answers [].

Two designs, both written out in the answer:

  • A, nsmallest at query time. A dict scores from name to score; top(k) calls heapq.nsmallest(k, ...) over the entries (-score, name), which sorts exactly like "score descending, then name".
  • B, a heap of entries. The same dict plus a heap of (-score, name) entries. add pushes a new entry, which leaves the player's old entries stale (their score is no longer the dict's). top(k) pops entries, drops the stale ones for good and keeps the first k valid ones, then pushes those k back, so the board is unchanged for the next query. Because points are at least 1, a player's score only grows, so no two entries are equal and a valid entry is never duplicated.

The oracle is sorted() of the dict by (-score, name), cut to max(k, 0) entries. heapq is the production answer for the k best of a stream (as earlier in this topic), and sortedcontainers (not imported) would keep the whole board sorted; here the point is which of the two designs is cheaper for which workload.

  1. Write both boards. Check both against the oracle on 300 seeded scripts of add and top over 12 players, plus an empty board, one player, scores that ascend, scores that descend and all-equal scores. Count the cases hit (a query on an empty board, k = 0, a negative k, a k larger than the number of players, equal scores in the answer) and count any Exception as a failure.
  2. Time the two designs on the plain code on an update-heavy workload (many adds, few queries) and a query-heavy one (few adds, many queries), 1,000 players, k = 10. For each workload print both times and the ratio, and give a verdict only when the ratio is at least 4 (a bar above 3x, because the update-heavy ratio moves between 1.6x and 3x from run to run). Under 4 print the ratio and "no verdict", with no direction. Assert the two designs gave the same answers on both workloads.
  3. Print a closing line built from the two verdicts, and the count of stale entries design B was still holding after the update-heavy workload (counted in a separate copy, never timed).
Q89The Log MergerMini-Project

A service writes one log file per machine. Each line is "timestamp source message": an integer timestamp, one word naming the machine, and a message that may contain spaces (for example "1042 web GET /index ok"). Each file is sorted by timestamp (equal timestamps are allowed), so the merged log is a k-way merge, as in DSA Topic 9's external sorter, which merged sorted runs from disk files. The merge here is lazy: it must produce the first N lines of the merged log without reading the rest of the files.

heapq.merge(*streams, key=...) does that and is stable: lines with equal timestamps come out in the order of the files they came from (file 0 first). Tokenise with str.split (not re): line.split(" ", 1)[0] is the timestamp and line.split(" ", 2)[1] the source.

One file is a problem: its machine's clock is jittery, so some of its lines are up to d places late, meaning every line is at most d places from where it belongs in sorted order. A merge assumes sorted input and would put such a file's lines out of order. The repair is the nearly sorted list from earlier in this topic: keep a heap window of d + 1 lines and always release the smallest (the entries are (timestamp, position, line), so equal timestamps keep file order). It is lazy as well: it reads at most d + 1 lines ahead.

The helpers timestamp(line), repair(lines, d) (a generator), counting(stream, counts, i) (a generator that adds 1 to counts[i] for every line it passes on) and max_displacement(lines) (the largest distance of a line from its place in the stable sorted order) are written out in the answer.

  1. Build four seeded files of 2,000 lines each, sources web, db, cache and auth, with db at most d = 3 places late (shuffle blocks of d + 1 consecutive lines of a sorted file, and assert max_displacement <= d). Show that merging without the repair gives output that is not sorted (print the first position where it goes backwards), then merge with it.
  2. Take the first N = 8 lines of the repaired merge. Print them, the number of lines per source among them, and the number of lines the merge pulled from the four streams. Assert that it is at most k + N, where k is the number of files, and print it beside the 8,000 lines in the files and the lines read from the db file. Assert that the first N lines equal the oracle: sorted() of all the lines in file order by timestamp (stable).
  3. Check the full merge, the first N and the per-source counts against that oracle on 300 seeded logs (0 to 5 files of 0 to 25 lines, some with a late file), plus no files, one file with one line, sorted files, equal timestamps in every file, and a file late by its whole length (reversed). Count each case hit and count any Exception as a failure.
Q90The CPU SchedulerMini-Project

One CPU runs processes (pid, arrival, burst, priority): integer times, burst >= 1 (the CPU time the process needs), a smaller priority number means more important, and pid is unique. The CPU hands out time slices of at most q ticks. This question simulates a stated rule and checks the simulation against a brute force of the same rule. It does not claim that the rule is the best possible: whether any rule is the best possible belongs to greedy algorithms, DSA Topic 20.

The rule. A process is ready once arrival <= clock. At every slice boundary the ready process with the smallest key runs next, for min(q, remaining burst) ticks, where the key is the static aging key from earlier in this topic, priority * c + arrival (the longer ago a process arrived, the smaller its key, so waiting lowers a low-priority process's effective priority number). With c = None there is no aging and the key is just priority. Equal keys are settled by a sequence number seq taken from one counter: a process gets its seq when it enters the ready set, and a process that used a whole slice and still has work left goes back with a new, larger seq, so equal keys take turns (round robin, as in DSA Topic 11's round robin with arrivals). When a slice ends at time t, first every process with arrival <= t enters the ready set (in (arrival, pid) order), then the preempted process goes back. If nothing is ready the clock jumps to the next arrival.

The result is the timeline [(pid, start, end), ...] of slices and each process's finish time, with turnaround = finish - arrival and wait = turnaround - burst.

  1. Write simulate(procs, q, c) with a heapq heap of (key, seq, pid), and the brute force simulate_scan which keeps the ready processes in a plain list and finds the smallest (key, seq, pid) by scanning it (it also counts, for the coverage below, the picks settled by seq, the idle jumps and the requeues).
  2. Print a table of one small workload of six processes with q = 2 and c = 3: pid, arrival, burst, priority, finish, turnaround and wait.
  3. Check both against each other on 300 seeded workloads (0 to 12 processes, q from 1 to 4, c from None, 1, 5, 20), plus an empty workload, one process, arrivals in order, arrivals in reverse order of the list, all arriving together and all with equal priority. Count the cases hit (simultaneous arrivals, an idle jump, a pick settled by seq, a requeue) and count any Exception as a failure.
  4. On a seeded workload of 150 processes (arrivals 0 to 200, bursts 1 to 4, priorities 0, 1, 2 with 60%, 30% and 10% of the processes, q = 2), print the longest wait per priority without aging and with c = 25. Build the closing line from those numbers.
Q91The Stream Statistics ServiceMini-ProjectMust Do

A monitoring service is fed integers one at a time and answers questions about the window: the last W items received (all of them while fewer than W have arrived). Build StreamStats(W, p, k) with this contract:

  • Construction: W (an int, at least 1), p (an int percent, 1 to 100) and k (an int, at least 0) are fixed once; anything else raises ValueError. add(x) raises TypeError when x is not an int.
  • Queries over the m items now in the window, with s the window sorted ascending:
    • minimum() and maximum(): s[0] and s[-1].
    • median(): the lower median, the item of 1-based rank (m + 1) // 2 (index (m - 1) // 2 of s).
    • percentile(): the nearest-rank p-th percentile, the item of 1-based rank (p * m + 99) // 100, computed in integers (so p = 100 is the maximum).
    • top(): the k largest window items, largest first, repeats kept: all m of them when m < k, [] when k == 0.
    • Before any item has arrived the window is empty: the first four return None and top() returns [].
  • Equal values are interchangeable, so ties need no rule for the answers; inside the heaps every item is the key (value, seq), where seq counts the items received, so no two keys are ever equal.

The design: a heap cannot delete from the middle, so an item leaving the window is deleted lazily: it stays in its heap as a stale entry (its seq is older than the window's oldest) and is thrown away only when it reaches a top. Minimum and maximum each use one heap whose stale tops are skipped. The median and the percentile each use two heaps: a max-heap low (negated keys in a heapq list) holding exactly the r smallest live keys, so the answer is low's top, and a min-heap high holding the rest, with counters of the live keys on each side (a heap's length counts stale entries too). An item that leaves is on low's side exactly when its key is at most low's live top. top() calls heapq.nlargest(k, ...) over the window. Lazy deletion alone lets stale entries pile up deep in a heap, so a heap holding more than 2W entries is rebuilt from its live ones with heapify.

Two heaps for a running median, lazy deletion over a sliding window, stale tops in a window maximum and nlargest were each built on their own earlier in this topic; the work here is putting them behind one stated API.

  1. Write StreamStats with add, the five queries and the rebuild. State each method's time and space with W and k named, and argue why the rebuild keeps add at O(log W) amortised.
  2. Show the contract (each bad argument, the empty window, a float) and trace W = 4, p = 75, k = 2 on 5, 1, 4, 1, 9, 2, 6, checking each row against sorting the window.
  3. Check every query after every item against sorting the window, on 300 seeded streams of 0 to 79 items: empty, single, ascending, descending, all-equal and many duplicates, with W = 1, k = 0, k > W and p = 100 among them. Count each case hit, and catch every Exception as a failure.
  4. For 20,000 random, ascending and descending items with W = 100, print the most entries the six heaps held at once against the bound the rebuild gives, the stale entries skipped, and the entries the rebuilds copied per item.
Q92The Print FarmMini-Project

A print shop has m printers, ids 0 to m - 1. Jobs are (id, arrival, pages, priority) with integer minutes; a printer prints one page a minute, so a job takes pages minutes, and a smaller priority number is more urgent. The rule, exactly:

  • At any minute, first every printer that finishes then becomes free, then every job arriving then joins the queue.
  • Then, while a printer is free and a job is waiting, the free printer with the smallest id takes the waiting job with the smallest priority, ties going to the earlier arrival and then the smaller id. A job runs to the end once started.
  • ValueError for m < 1, a repeated job id, an arrival below 0 or pages below 1. No jobs gives {}.

Keep three heaps: finish events (end, printer), waiting jobs (priority, arrival, id) and free printer ids.

  1. Write print_farm(m, jobs) returning {id: (printer, start, end)}, with its time and space (n jobs, m printers).
  2. Print a day on 2 printers with simultaneous arrivals, two printers freeing at the same minute, equal priorities and an idle gap: each job's printer, start, end and wait, and each printer's printing minutes.
  3. Check it against a brute force of the same rule that keeps no heaps: at each moment something can change, it scans every job not yet started and every printer. Use 300 seeded days (0 to 14 jobs, 1 to 4 printers), assert that no printer runs two jobs at once and no job starts before it arrives, and count the empty days, single jobs, one-printer days, days with more printers than jobs, jobs that waited, priority ties, jobs started on a printer the minute its previous job ended and printers left idle all day. Catch every Exception as a failure.
  4. Say in one line what is and is not claimed: the rule is simulated and checked, not shown to be the best rule (that is a question for greedy algorithms, DSA Topic 20).
Q93The Priority InboxMini-Project

An inbox ranks unread, visible messages by importance (higher first), then by time (earlier first), then by id. Messages are (id, time, sender, importance). The contract:

  • receive(id, time, sender, importance) first advances the clock to time, then adds the message unread. ValueError for an id used before or a time before the clock.
  • top(k): the ids of the k best visible unread messages, best first; all of them when fewer; [] when k <= 0.
  • mark_read(id): True if it was unread (visible or snoozed), False if already read; KeyError for an unknown id.
  • snooze(id, until): hides an unread message until the clock reaches until, which must be later than now (ValueError otherwise); a second snooze replaces the first; False for a read message; KeyError for an unknown id.
  • advance(now): moves the clock (ValueError if it goes back); every snoozed message with until <= now becomes visible again, keeping its original time for ranking.

Use a heap of (-importance, time, id, version) entries and a second heap of (until, id, version) wake-up entries. Reading or snoozing never searches the heap: it changes the message's record (read flag, version), which makes the old entry stale. top(k) pops until it has k valid entries, throws stale ones away (counted) and pushes the valid ones back. Waking pushes a fresh entry. Re-pushing with a version and skipping stale entries is the updatable queue's idea, and reading by marking is cancelling by marking, both from earlier in this topic; the inbox puts them together with a wake-up heap.

  1. Write Inbox and state each method's time and space (n entries held, k, s stale entries skipped, w wake entries).
  2. Trace a short morning: four messages, a snooze, reading a message twice, top with k = 0 and k larger than the inbox, a message waking exactly at its until, and each error.
  3. Check it against BruteInbox, a dict scanned and sorted on every call, on 300 seeded scripts of up to 59 operations, comparing every result (or exception type name) and asserting after every operation that each visible unread message has exactly one valid entry and that both lists are heaps. Count each case hit (empty top, k above the visible count, k <= 0, reading a read or a snoozed message, snoozing a snoozed one, waking exactly at until, importance ties in an answer, each error) and catch every Exception as a failure. Print the stale entries skipped and the most entries held against the most unread messages.
Q94The Elevator ControllerMini-Project

One elevator car serves floors 0 to F - 1. It starts at floor 0, heading up, and moves one floor a minute. A request is (time, floor): someone wants the car at that floor from that minute on. The rule, exactly:

  • At each minute, every request that has arrived joins the pending set, and every pending request for the car's floor is served at once (its wait is the minute served minus its time).
  • If any pending request lies ahead in the current direction, the car moves one floor that way. If none does but some lie behind, it turns round and moves one floor. If none is pending, it stays where it is and keeps its direction.
  • ValueError for F < 1, a negative time or a floor outside 0..F - 1. Requests may come in any order; equal times are taken in input order.

The heap version keeps pending floors above the car in a min-heap of (floor, request index) and those below in a max-heap (negated floors); a new request joins the heap for its side, or is served on the spot. Instead of ticking every minute it jumps: to the next stop (the top of the heap ahead), or to the next request's arrival if that comes first, moving the car part of the way.

  1. Write elevator(F, requests) returning (total floors travelled, waits in input order), with its time and space for r requests.
  2. Print a morning in a 10-floor building: each request's wait, the travel, the average and the longest wait.
  3. Check it against a brute force that ticks minute by minute and scans every pending request each minute, on 300 seeded days (0 to 11 requests, F from 1 to 11). Count the empty days, single requests, one-floor buildings, requests served on the spot, turn rounds, requests arriving while the car is on its way, idle spells and repeated floors, and catch every Exception as a failure.
  4. Say in one line what is and is not claimed: the rule is simulated and checked, not shown to minimise travel or waiting (greedy algorithms, DSA Topic 20).
Q95The Matching EngineMini-Project

An exchange matches limit orders (id, side, price, qty), side "B" (buy) or "S" (sell), in arrival order, by price-time priority:

  • A new buy trades against the lowest-priced resting sell while that price is at most its own; a new sell against the highest-priced resting buy while that price is at least its own. Among equal prices the earliest resting order goes first.
  • Each trade is (maker id, taker id, price, qty) at the resting order's price. Fills can be partial; whatever is left of the new order rests in the book.
  • ValueError for an id used before, a side other than "B" or "S", or a price or quantity below 1. cancel(id) returns True if the order was resting and removes it, False for an unknown, filled or already cancelled id.

Keep bids in a max-heap of (-price, seq, id) and asks in a min-heap of (price, seq, id), with seq counting resting orders. A cancel only removes the id from a dict of live orders; its heap entry goes stale and is skipped when it reaches a top. DSA Topic 12's order book kept each price level as a linked list inside a sorted list of prices, so a cancel unlinked one node in O(1); here a cancel is O(1) too, but its entry stays in the heap until it surfaces.

  1. Write Engine with submit, cancel and book() (resting orders, bids best first then asks best first), with each method's time and space. Add a rebuild of both heaps from their live entries when a cancel leaves more entries than twice the live orders (rebuilding from the live entries when the stale ones outnumber them is the timer service's compaction, earlier in this topic; the twice-live trigger across two heaps is what is new).
  2. Trace four resting orders, a cancel (twice, and of an unknown id), a buy that sweeps two levels with a partial fill, and each refused order.
  3. Check it against BruteEngine, which keeps one list of resting orders and scans it for every match, on 300 seeded scripts of up to 60 events, comparing every trade list, cancel result, exception type and the whole book after every event. Count trades that missed (no cross), full and partial fills, sweeps, cancels of live and of gone orders, refused orders and orders arriving to an empty opposite side, and scripts where a rebuild ran; catch every Exception as a failure. Print the stale entries skipped and the most heap entries against the most live orders, and assert the bound the rebuild gives.
Q96Explaining It ColdInterview

"You've got five minutes and no notes: tell me what a heap is and when you'd reach for one." Answer out loud, and back every point you make with two or three lines printed by code you ran, so that nothing rests on memory. Every "X beats Y" must come from a count computed in the answer (a verdict only when one count is at least twice the other; otherwise say "within 2x").

  1. The property and the layout: a complete binary tree stored in a list, every parent at most its children, parent (i - 1) // 2 and children 2i + 1, 2i + 2; a heap is not a sorted list.
  2. Push and pop, with costs counted: a push that is a new maximum, a push that is a new minimum, and one pop, against floor(log2 n).
  3. Heapify in O(n): comparisons on descending input against twice the sum of the slot heights (n - popcount(n)), and against pushing one item at a time.
  4. heapq and negation for a max-heap; whether this Python has public max-heap functions, printed with hasattr.
  5. The stable priority queue: why (priority, item) breaks on equal priorities with dict items, and how a counter fixes it and keeps arrival order.
  6. Top-k with nlargest against sorted(), and two heaps for a running median.
  7. When a heap buys nothing over sorted(): you need every item in order, k is near n, or the input is already sorted. Let the counts say which of these sorted() actually wins.

The helpers levels, is_heap, sift_up, sift_down, heapify, MinHeap, Key (a wrapper whose < adds 1 to Key.compares) and PQ (a stable priority queue on heapq with a counter) are written out in the answer.

Q97Diagnosing By ReasoningInterview

"Here are five heap functions from code review. Each one is wrong. Before you run anything, tell me the smallest input that breaks each, and why. Then prove it."

  • D1 is_heap_d1(a): for every parent i < len(a) // 2 it checks a[2i + 1] and a[2i + 2].
  • D2 heapify_d2(a): calls sift_up on every slot from the last back to 1.
  • D3 kth_largest_d3(xs, k): returns heapq.nsmallest(k, xs)[-1] (the k-th largest is 1-based).
  • D4 merge_desc_d4(lists): list(heapq.merge(*lists, reverse=True)) on lists sorted ascending, to get every item largest first.
  • D5 drain_d5(h): for _ in h: out.append(heapq.heappop(h)) to pop a heap empty.
  1. Write down your predictions and the reasoning (in comments).
  2. Confirm each by a plain search in increasing size: D1, D2 and D3 over BED (every order of up to 7 distinct items, then every list over 0, 1, 2 of up to 7 items, shortest first; D3 with every k from 1 to n), D4 over tuples of 1 to 3 ascending lists over with up to 3 items in all, D5 over the heaps in BED. Print the smallest failing input beside the truth, assert the failure (an exception by its type name), and count how many inputs of the bed fail and how many of those raise.
  3. Give the fix for each in one line.

The helpers is_heap, sift_up and the BED lists are written out in the answer.

Q98Designing For OperationsInterview

"Design me a queue where I can take out either the smallest or the largest item, both fast." The contract: insert(x), pop_min(), pop_max(), peek_min(), peek_max() and len(); equal values are allowed; every pop and peek raises IndexError on an empty queue. Each operation should be O(log n) amortised for n items held.

The design to defend: two heapq heaps, a min-heap lo of (x, n, cell) and a max-heap hi of (-x, n, cell), where n counts inserts (so cells are never compared) and cell is one shared list [alive]. A pop from one heap sets cell[0] = False, and the other heap skips that dead entry when it reaches its top. Nothing is ever searched or removed from the middle: removal is a mark only.

  1. Write DEPQ, with each method's time and space. A heap keeps every dead entry until it surfaces, so also rebuild a heap from its live entries when its dead entries outnumber the live items.
  2. Check it against a sorted list (insort, pop(0), pop()) on 300 seeded scripts of up to 79 operations: empty pops, single items, ascending, descending and duplicate inserts, and assert after every step that each heap's length is the live count plus its dead count and that the dead never outnumber the live. Count each case hit and catch every Exception as a failure.
  3. Argue "amortised O(log n)" from counts, not by assertion: on 50,000 inserts with pops (ascending inserts with pop_min every step; random inserts popped from either end), print the most entries held against the most live items, the dead entries popped, the entries the rebuilds scanned, and the heap pops and rebuild scans per operation, and assert the bounds your argument needs. (Rebuilding from the live entries when the dead ones outnumber them is the timer service's compaction, earlier in this topic; what is new is the two heaps sharing entries.)
  4. Name and cost the alternatives in one line each: a sorted list with bisect, a min-max heap (one array; not built here), a search tree (DSA Topic 14).
Q99The Mock Interview: A News FeedInterview

"Show the 10 newest posts from the people I follow." Each followed user's posts are a list of (time, post id), newest first, equal times by post id. The merged feed is newest first, ties by user id, then by post id: the ascending order of the key (-time, user, post id). A page shorter than 10 is fine when fewer posts exist.

  1. First answer: gather every post and sort, O(P log P) for P posts. Better: merge lazily. Heapify each user's newest post, pop the best, push that user's next post, and stop after 10: O(k + 10 log k) for k users. Write both and trace a feed of four users (one with no posts, equal times across users).
  2. Follow-up: "the next page." The cursor is the last post shown. For each user find the first post after the cursor by binary search on (-time, post id), then merge lazily from there. Check pages against gather-and-sort on 300 seeded inputs (no users, users with no posts, one user, equal times, a page larger than the feed), walking every page to the end, and catch every Exception as a failure.
  3. Follow-up: "one user has 100,000 posts" and "you follow 1,000 people." Count the posts each page touches against P.
  4. Follow-up: "when would you just sort everything?" For the whole timeline (every post, in order) count comparisons per post for both at 1,000 users, and time both (min of 3): print the time ratio only, since the merge measurement earlier in this topic showed such ratios moving under load. Close with lines built from the counts.

The helpers Key (a wrapper whose < adds 1 to Key.compares) and best_of (the smallest time of 3 runs) are written out in the answer.

Q100CapstoneInterviewMust Do

"Build the dispatch board for an emergency service, for one day." Times are integer minutes. A call is (id, arrival, severity, duration), where severity 1 is the most urgent; there are u identical units. The rule and every contract:

  • Dispatch: while a unit is free and a call is waiting, the waiting call with the smallest severity is dispatched, ties going to the earlier arrival, then the smaller id. The unit is busy for the call's duration minutes and is free again at dispatch time + duration. A call's wait is its dispatch time minus its arrival.
  • Changes are (time, "cancel", id, None) or (time, "regrade", id, new severity). A cancel removes a waiting call; a re-grade gives a waiting call a new severity and keeps its arrival for ties. A change naming a call that is not waiting at that moment (unknown, not arrived yet, already dispatched or already cancelled) is ignored and counted.
  • One moment: everything at the same minute is handled together: units that come back first, then arrivals (by id), then changes (in list order), then dispatching. So a call arriving the moment a unit frees competes for that unit with every waiting call, and gets it at once (wait 0) when it is the most urgent.
  • u = 0 is allowed: no call is ever dispatched, and each ends "never dispatched". An empty day gives an empty report. ValueError for u < 0, a repeated call id, an arrival below 0, a severity or duration below 1, a change time below 0, an unknown change kind, or a re-grade below 1.

The design: an event queue of (time, n, (kind, data)) entries, where n counts pushes so events of one minute keep their push order and data is never compared, drives the clock. The board is a heap of (severity, arrival, id) entries with a version number. A cancel only marks the call; a re-grade bumps the version and pushes a new entry; a popped entry whose call is no longer waiting, or whose version is old, is stale and skipped (counted, along with the most entries the board ever held). Re-pushing with a version and skipping stale entries, and cancelling by marking, are ideas used earlier in this topic; here they run together on one board. These helpers are written out in the answer: is_heap(a) checks that no item of a list is smaller than its parent; MinHeap is a hand-written binary min-heap (with sift_up and sift_down); StablePQ is a priority queue on MinHeap with entries (priority, n, item); PQ is the same queue on heapq; best_of(fn) is the smallest time of three runs.

  1. Write dispatch(u, calls, changes, checkpoints, make_queue, check) returning, for each call, ("dispatched", time, wait, severity) (the severity it was dispatched at, after any re-grade), ("cancelled", time) or ("never dispatched",); the waiting board, sorted, at each checkpoint (after everything at or before that minute); and the counts. With check on, after every minute assert that both queues pass is_heap and that every waiting call has exactly one valid board entry and nothing else does. State the time and space (c calls, h changes), with the checks off and with them on.
  2. Show each contract error, an empty day and a day with no units. Then run a day on two units with a re-grade, a cancel of a call that has not arrived yet, a cancel while waiting, re-grades and cancels after dispatch, and an arrival the moment a unit frees: print each call's outcome, the board at three checkpoints, the longest wait per severity and the counts.
  3. Check every outcome and every board against a brute force of the same rule that keeps no heaps (each step scans every call, change and unit) on 300 seeded days, with both PQ and StablePQ, checks on. Count the empty days, the days with no units, cancels while waiting, ignored changes, re-grades while waiting, stale entries skipped and arrivals at a return, and catch every Exception as a failure.
  4. Run one busy day (10,000 calls, 2,000 changes, 6 units) on PQ and on StablePQ, checks off: time the whole day, and the day's queue pushes and pops replayed alone, and print hand-written / heapq for each. A verdict needs a ratio of at least 2 that stays at 3x or more with six copies of the program running at once; print the ratio alone otherwise. Build the closing recommendation from what was measured and checked.
  5. Say in one line what is not claimed: the board simulates a stated rule; it is not shown to give the shortest waits (greedy algorithms, DSA Topic 20).

Stuck? Solve it with a mentor.

Your first 1-on-1 session is free.

Book my free session