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.
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.
- Write
is_heap_tree(root): True when no node is smaller than its parent, checked node by node with a stack (no recursion). - Paste
is_complete(root)as DSA Topic 13 wrote it: True when the tree is complete, found by a level-order walk with adequethat keepsNonechildren in the queue, so that once aNonehas been taken out no real node may follow. - 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). - Count the heaps among all orders of
1..kfork = 0..7(byitertools.permutations) and assert that the root is the minimum in every one of them.
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.
- 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. Printlevels([1, 3, 2, 7, 4, 5]). - Assert for every length
n <= 100that leveldstarts at index2^d - 1, that every level but the last is full, and that there aren.bit_length()levels. - Build three beds of test lists, written out in the answer:
PERMS, every order of0..k-1fork = 0..7(5,914 lists);DUPS, every list of length 0 to 7 over the values0, 1, 2(3,280 lists); andBED = PERMS + DUPS(9,194 lists). - Round trip:
from_level(a)builds the tree of a list (TreeNodeandfrom_levelare written out in the answer: from a level-order list withNonegaps,from_levelreturns the root). A level-order walk of that tree with adequemust give back exactlya, with noNonein it, for every list ofBED.
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.
- Show the derivation as an assertion for every level
d < 12and everyj < 2^d: the left child's index is2^(d+1) - 1 + 2j, which equals2i + 1fori = 2^d - 1 + j. - Write
parent(i),left(i)andright(i)with their contracts:parentneedsi >= 1and gives(i - 1) // 2; the child formulas give2i + 1and2i + 2, which may lie past the end of the list, so every caller tests< len(a)first. - Assert
parent(left(i)) == parent(right(i)) == ifor everyi < 10^4. - Check the formulas against a real tree:
from_level(written out in the answer: it builds the tree of a level-order list withNonegaps and returns the root) hangs nodes under each slot. On every list ofBED(every order of0..k-1and every list over0, 1, 2, each of length 0 to 7: 9,194 lists, built in the answer), walk the tree with adequebeside the slot numbers and assert that the children it holds are exactly the items atleft(i)andright(i)when those are< len(a), andNoneotherwise. - Print
i,parent(i),left(i)andright(i)fori = 0..6.
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).
- Write
is_heap(a): each item against its parent only, O(n). - 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, orNone; andheap_ok(a)on top of it. Cost O(n log n). - Argue in three printed lines why the parent check is enough:
<=chains along every path from the root. - Confirm that
is_heapandheap_okagree on all 9,194 lists ofBED(every order of0..k-1and every list over0, 1, 2, each of length 0 to 7) and count the heaps. - Broken variant
is_heap_left_only, which checks only left children (odd slots): scanBEDfrom the shortest list, orders before lists with repeats, for the first list it accepts butis_heaprejects, and show it beside the truth. Count how many lists ofBEDit gets wrong. - Print
first_bad_pairfor a few near misses.
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.
- Assert that the two layouts agree for every
i < 10^4: the 0-based sloti0is the 1-based sloti0 + 1, so the 1-based parent and children ofi0 + 1are the 0-based ones plus 1. - Write
is_heap_1(a)for a list whose slot 0 is unused, andis_heap(a)for the 0-based list. Checkis_heap_1([None] + a) == is_heap(a)on every list ofBED(every order of0..k-1and every list over0, 1, 2, each of length 0 to 7). - The path from the root to slot
i(1-based) spellsiin binary after its leading 1, with 0 for left and 1 for right. Print the paths fori = 1..15and assert the rule for everyi < 2^12by walking from slot 1.
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].
- Write
peek(a)with the empty-heap contract and show the error once. - Take the heaps of
BED(every order of0..k-1and every list over0, 1, 2, each of length 0 to 7; a heap is a list in which no item is smaller than its parent) and assertpeek(a) == min(a)on every non-empty one. - Assert
min(a[1:3]) == sorted(a)[1]on every heap with two or more items, and print how many there were. - Broken variant
second_b6, which returnsa[1]: scan the heaps ofBEDfrom 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.
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.
- Print the four-line argument that sift-up restores the heap rule.
- Write
sift_up(a, i)and a classMinHeapwith__init__,__len__,peek(IndexError when empty),pushand_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, andheap_ok(a)is True when no item is smaller than any of its ancestors. - Trace pushes of 5, 3, 8, 1, printing
levelsafter each push. - Check on every list of
BED(every order of0..k-1and every list over0, 1, 2, each of length 0 to 7: 9,194 lists): pushing the list's items one at a time keepsis_heapandheap_okTrue after every push and holds the same items (equal when sorted). Also assert that no push makes more thanfloor(log2 n)swaps, withnthe heap size after the push, using a counted copy of the climb that gives the same list. - Broken variant
push_b7, which loopswhile i > 1, so slot 1 is never compared with the root: scanBEDfrom the shortest list for the first one it builds into a non-heap, and show it beside the right result.
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.
- Write
sift_up(a, i),push(a, x)andKey(every<between two keys adds 1 toKey.compares). - A sorted list is already a heap. Take a heap of
10^5keys 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 costsfloor(log2 n)fornthe size after the push (n.bit_length() - 1). - Build heaps by
npushes, one at a time from an empty list, forn = 10^3, 10^4, 10^5and three input orders: a seeded random order of0..n-1, ascending and descending. Print comparisons per push. - Assert what the counts show: ascending costs
n - 1comparisons in all; descending costs exactly the sum offloor(log2(i + 1))overi = 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).
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.
- Write
sift_down(a, i, n), which siftsa[i]down insidea[0:n](slots fromnon are ignored), and completeMinHeapwithpopand_sift_down. These helpers are written out in the answer:sift_up(a, i)swapsa[i]up while it is smaller than its parent;MinHeaphas__init__,__len__,peekandpush(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;Keywraps a value so that each<adds 1 toKey.compares. - Write
random_list(n, rng, span), which returns exactlynints drawn fromrange(span)with a seededrandom.Random, and raisesValueErrorwhenn < 0or whenspan < 1andn > 0(show the error once). Write the brute-force queueListPQ: an unsorted list whosepushappends and whosepopscans for the smallest item and removes the earliest of equal ones (IndexErrorwhen empty). - Trace the heap built by pushing 5, 3, 8, 1, 9, 2, then pop everything, printing
levelsafter each pop. - Check: on every list of
BED(every order of0..k-1and every list over0, 1, 2, each of length 0 to 7: 9,194 lists), pushing the items and popping to empty givessorted. Assert that a pop costs at most2 * floor(log2 m)comparisons,mthe heap size after the pop, on a heap of 1,023Keys. - Fuzz: 300 seeded scripts of mixed pushes and pops (values from
0..9) run againstListPQ, withis_heapchecked 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 anyExceptionas a failure. - Broken variant
pop_b9, which overwrites the root with the last item before saving the root: scan the heaps ofBEDfrom the shortest for the first one where it returns the wrong item, and show it beside the truth.
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.
- Show each case with the heap written earlier in this topic (its
MinHeapwithpush,popandsift_downis written out in the answer): the empty pop and its message, a single item, two items, and five equal items. - Broken variant
pop_b10a, which savesa[0]and then writesa[0] = a.pop(): scan the heaps ofBED(every order of0..k-1and every list over0, 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 oncepop()has run). - Broken variant
pop_b10b, which returnsa[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. - Then pop the real heap to empty on every list of
BED, plus one more pop on each, and count theIndexErrors: one per list.
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".
- Sift slot 0 of
[5, 1, 2]with the wrong rule (swap with the larger child) and print the result and the brute-forcefirst_bad_pair(the first item that is smaller than one of its ancestors). Then sift with the right rule and print the result. - 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.
- 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.
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.
- Write
heapifyand trace it on[9, 4, 7, 1, 8, 2, 6, 3, 5], printinglevelsafter each sift. - Check
is_heap, the same items (compared sorted) and aNonereturn on every list inBEDand on 300 seeded random lists of 0 to 300 items, and checkheap_ofthe same way. - 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
BEDin order of length) and print it beside the truth. - Count comparisons and swaps (one
<is a comparison, one exchange of two slots is a swap) forheapifyagainst pushing the items one at a time, on random, ascending and descending lists of 1,000 and 10,000 items. State the cost:heapifyis 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.
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.
- 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 everynbelow 3,000. - So
heapifymakes at mostn - popcount(n)swaps and at most twice that many comparisons. Assert both on every list ofPERMSand print the worst swaps for eachkbeside the bound. - 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 sloti, so Theta(n log n) in total) beside it. - Time
nhand-written pushes againstheapifyat 100,000 items on random and on descending input, and decide only from printed ratios.
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.
- Write
heapify_maxwithsift_down_maxandis_max_heapand check, on every list inBED(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. - For numbers there is a second way: store
-xin a min-heap, since the smallest-xis the largestx. Check that the two ways pop the same values on 300 seeded lists that hold negatives and zero. - 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.
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.
- Print the levels of a heap of 100,000 and of 1,000,000 items, and assert
n.bit_length()equalsfloor(log2(n)) + 1for everynbelow 100,000. - 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.
- 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 sizenat that moment.
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.
- Write
heapsort(a)and check it againstsorted()on every list inBEDand on 300 seeded random lists of 0 to 300 items (plus sorted, reverse-sorted and all-equal lists). - A student sifts with
len(a)instead of the shrinkingend(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. - Count comparisons per
n * log2(n)for heapsort and forsorted()on random lists, and on an already sorted list of 10,000 items (sorted()finds the run, DSA Topic 9). Then time heapsort againstsorted()at 100,000 random items and decide from the printed ratio.
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.
- 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. - 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. - The fix when order among equals matters: sort
(key, position)pairs, so no two keys are equal. Count the lists that still fail.
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.
- Push
(1, "write"),(1, "backup"),(1, "email")(in that order) into a min-heap and print the pop order beside the arrival order. - 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. - 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.
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.
- Write a class
Spythat 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. - Write
Jobwithpriorityandpos(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. - State the lesson from the computed result.
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.
- 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.
- The bug B20:
sift_upwith<=, swapping equal items. Push 1,000 and 10,000 equal items and compare the swaps with the sum offloor(log2(i + 1))over the slotsi(an item pushed into sloticlimbs to the root), asserting they match. - 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.
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.
- Write
find(a, x), the index of the first slot holdingx(orNone), and say what it costs: a heap is only partly ordered, so finding an item is a scan. - Write
change_at(a, i, new): seta[i] = newin 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, printinglevelsafter each. - 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).
- 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.
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.
- Write
remove_at(a, i): remove and returna[i]in place, moving the last item into slotiand 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. - 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. - 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.
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.
- Write
k_smallest(items, k):heap_of(items)thenkpops, smallest first. Contract:k <= 0gives[], andk >= ngives every item, sorted. Check it againstsorted(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. - With the
Keywrapper that counts every<, count the comparisons for n = 10,000 distinct random items: heapify plus the firstkpops, for k = 1, 10, 100, 1,000 and 10,000, beside the comparisons of onesorted()of the same items. - Find the smallest
kin 1, 2, 4, 8, ... (by doubling) at which popping makes more comparisons than sorting, and print it as a share of n. - Conclude from the printed numbers only. (DSA Topic 9's top k by sorting, selecting or scanning is the starting point; keeping only
kitems while a stream arrives is the next level of this topic.)
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.
- 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. - Measure a heap of linked nodes with
val,left,rightandparentreferences, 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. - 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). Printsys.getsizeofof an int, a 2-tuple, a 3-tuple and a node beside them. - State the node-to-array ratio from the printed numbers.
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.
- Write
find_in_heap(a, x)returning(index or None, slots visited). Walk from the root with a stack. Stop atx. Never go below a slot holding something larger thanx(everything under it is larger too): only a slot holding an item smaller thanxopens its two children. - 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
ccount the items smaller thanx; print the visits and assertvisits <= 2c + 1. - 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). - Show the student bug that takes the last item
a[-1]as the maximum, on the first failing heap in a scan by size. - Show that the array is not sorted, so the k-th smallest costs k pops.
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.
- Write
top_k_largestwith the size-kmin-heap: push until it holdskitems, then compare each new item with the root, and replace the root (seta[0], sift down) only when the new item is larger. State time and space. - 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 everykfrom -1 to n + 1, and on 300 seeded streams fed as generators (so the list is never available), counting the contract cases hit. - Count comparisons per item with
Keyon 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. - Show the student bug that keeps a max-heap of the
kitems (its root is the largest), on the smallest failing input found by a scan, beside the truth.
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).
- Write the class.
k < 1raisesValueError. Eachaddcosts O(log k) and the object holds O(k) items however long the stream is. - Check after every
addagainst a sorted list of everything so far (kept withinsort), on 300 seeded streams with duplicates for k = 1, 3 and 10. Count the adds that returnedNoneand the adds that did not, and print the largest the heap ever got. - Feed 100,000 scores to
KthLargest(3)and print the heap's size at the end.
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).
- Write
k_closest(points, target, k).k <= 0gives[], andk >= ngives every index. State time and space. - Check against sorting all indices by
(squared distance, index)on 300 seeded point sets with coordinates in -3..3 (many points tie), for a randomkfrom -1 to n + 1. Count how many sets had ties at the cut. - 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.)
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.
- Write
merge_kwith the heap. State time and space withNitems inklists. - Check against
sorted(chain(*lists))on 300 seeded inputs that include empty lists, a single list, no lists and duplicates across lists. - Show stability: merge three lists of words by
key=lenand compare withsorted(chain(*lists), key=len), which is stable. - 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 inKey), beside2 * log2(k), and assert the count stays within3 * log2(k) + 1per 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.
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.
- Write
merge_lazy(iterables, stats=None); whenstatsis a dict it records the peak number of entries held. Check againstsortedon 300 seeded inputs of lists, tuples and iterators, with empty sources and duplicates, and assert the peak never exceedsk. - Merge 1,000 endless generators (generator
jyieldsj, j + 1000, j + 2000, ...) and take the first 10 items withitertools.islice. Count the items pulled out of the generators, and assert at mostk + 10. - 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. - One line: the
mergefunction of theheapqmodule does this, later in the topic.
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).
- Write
StablePQwithpush(priority, item),pop()(returns(priority, item)),peek(),len, and anIndexErrorwhen it is empty. Push five tasks, three of them with the same priority, and print the pop order beside the arrival order. - 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 aMinHeap: find, by running the pushes, which push of priorities 5, 4, 3, 2, 1, 1 raisesTypeError, 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. - Check
StablePQagainstListPQon 300 seeded scripts of pushes and pops with priorities 0 to 3, and count the pops that hit an empty queue.ListPQholds a small wrapper that compares priority alone, so its scan decides every tie by arrival.
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).
- Write
UrgentPQon the stable queue:push(priority, item)stores-priority, andpop()returns(priority, item)with the original sign. The stable queueStablePQ(a min-heap of(priority, n, item)entries) and its helpers are written out in the answer. - Write
BrokenUrgentPQthat 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 thanUrgentPQ. Print both orders. - Check both against
ListPQ(an unsorted list whosepopscans 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.
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).
- Write
RunningMedianwithadd(x)(returns the median so far),median()(anIndexErrorwhile 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. - Write
BrokenMedian, which moves items fromlowtohighonly and never back. Find onBED, shortest list first (orders before lists with repeats at each length), the first stream where it differs from the truth, and print both answers. - Check
RunningMedianagainst a sorted list kept withbisect.insort(DSA Topic 5's sliding median kept its window that way, and DSA Topic 14 found the lower median of a changing set withselect) on every list ofBEDread 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.
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.
- Write
IdAllocatorwithallocateandrelease, on the hand-writtenMinHeap(a binary min-heap in a list withpush,popandlen, comparing with<only;sift_upandsift_downare its two moves), written out in the answer. Trace a short script. - Write
BruteIds, which scans 0, 1, 2, ... for the first id that is not in a set of ids in use. - Check the two against each other on 300 seeded scripts of
allocateandrelease, where some releases name an id that is not in use. Count the reused ids and theValueErrors.
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.
- Write
last_stone(stones)on the hand-writtenMinHeap(a binary min-heap in a list withpush,pop,peekandlen, comparing with<only;sift_upandsift_downare 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]. - Write
last_stone_sorted, the oracle: a sorted list where each round pops two from the end andinsorts the difference. - Check them against each other on every list of
BEDread 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.
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.
- Write
kth_smallest(matrix, k)on the hand-writtenMinHeap(a binary min-heap in a list withpush,popandlen, comparing with<only;sift_upandsift_downare its two moves), written out in the answer. Return the value and the number of pushes, and give it an optionalloglist that every push appends(row, column)to (it is never read by the search). Trace a 3 x 3 matrix. - 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 toR*C - 1, sizes from 1 x 1 up to 3 x 3) andkwhere it gives a different answer from the truth, and print both. - 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 forRxCmatrices) and reads one cell per step. - Check the heap against
sorted(all cells)[k - 1]on 300 seeded matrices,kout of range included. Assert that no cell was pushed twice and that pushes stay at or belowR + k.
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.
- Write
k_smallest_pairs(a, b, k)on the hand-writtenMinHeap(a binary min-heap in a list withpush,popandlen, comparing with<only;sift_upandsift_downare its two moves), written out in the answer. Return the index pairs, the number of pushes and the largest the heap grew. Tracea = [1, 7, 11],b = [2, 4, 6],k = 5. - Check it against the brute force that sorts every pair by
(sum, i, j)and takes the firstk, on 300 seeded inputs: empty lists, a single pair, all-equal lists, many repeats andklarger thanlen(a) * len(b)included. - Assert on every input that pushes are at most
min(k, len(a)) + kand that the heap never holds more thanmin(k, len(a))entries.
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).
- Show the four calls on a small list, then run 300 seeded scripts of pushes, pops and "extend, then
heapify" on aheapqlist and aMinHeapside by side. Assert thatis_heapholds after everyheapqcall and that both give the same value at every pop (or both raiseIndexError). - 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 whereheapq.heapifyand the hand-writtenheapifyleave different arrays (separately for orders and for lists with repeats), print the smallest one, and assert that the pop sequences are equal on all ofBED. - Time
heapqagainst the hand-written heap at 100,000 random ints, taking the smallest of 3 runs ofbest_of: pushing all of them, popping all of them, andheapifyof a copy. Print each ratio, and draw a verdict only from a printed ratio of at least 2. - Say why, from what the module holds: which of its functions are C functions in CPython and which are Python code. Then name what
heapqcannot 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.
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.
- Print
hasattr(heapq, "heappush_max")and build one sentence from it that says whether this Python needs the negation trick. - Write
MaxHeapQon aheapqlist for numbers:push(x),pop()(the largest),peek()(the largest, left in place),len, and anIndexErrorwhen it is empty. Trace pushes of3, 1, 4, 1, 5, printing the stored list beside the items popped. - Show that negation is for numbers only:
-"abc"and-("a", "b")raiseTypeError. Catch both and print the messages. - Write
BrokenMaxHeapQ, whosepopforgets 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. - Check
MaxHeapQagainstsorted(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.
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.
- 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 bykeyalone throughkey=lambda p: p[0], so theidshows whether ties keep their input order. Includekbelow 1 and above the length, an empty input, a single item, sorted, reverse-sorted and all-equal inputs, and count each. - In CPython these two are written in Python (
Lib/heapq.py), not C, and they take shortcuts:minormaxwhenkis 1, andsorted()whenkis at least the number of items. Count comparisons with theKeyclass (it counts every<between two keys; counting is for counting only, never for timing) to see them:nsmallest(1, xs)andnlargest(1, xs)againstn - 1, andnsmallest(n, xs)againstsorted(xs). - Count comparisons at
n = 100,000random items fornlargestwithk= 10, 100 and 1,000, againstsorted()of the whole list, and fornlargest(10)on ascending input (every new item beats the smallest kept one). Print each count as a multiple ofn.
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.
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.
- Show both on
[3, 5, 9]withx = 1(andheappushpopwithx = 7): what each returns and what each leaves behind. - Print the edge cases:
heappushpop([], 5)returns5;heapreplace([], 1)andheappop([])raiseIndexError(print the message). - Check both against their two-call versions (
pushthenpop;popthenpush) on 300 seeded scripts that mix pushes, pops,heappushpopandheapreplace, 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 everyExceptionas a failure. - Count comparisons on 10^4 operations against a heap of 1,000 items (through a counting wrapper), for random
xand for anxbelow every item, each against its two-call version. State the saving from the counts.
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.
- Merge two lists of
(word, source)records withkey=lenand show that equal lengths come out with inputAbefore inputB, and the other way round when the inputs are swapped. Assert it equalssorted(chain(a, b), key=len). - Check
mergeagainstsorted(chain(...))on 300 seeded cases of 0 to 5 sorted inputs (with and without akey, with duplicates, empty inputs, one input and all-equal items). Count how many cases hit each kind and catch everyExceptionas a failure. One line: withreverse=Trueevery input must be sorted largest first (its trap comes later in this topic); print that the merge of two descending lists matchessorted(..., reverse=True). - Merge
kendless generators (generatorjyieldsj,j + k,j + 2k, ...) fork= 10, 100 and 1,000, take the first 10 items withitertools.islice, and count the items pulled out of the generators. - A student's bug (B42 in the code): trusting
mergewith 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 writechecked_merge, a generator that raisesValueErrorat the first descent in any input, and show it on that pair and on every pair in the scan.
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.
- Check
StablePQ,PQandListPQagree on 300 seeded scripts of pushes, pops and peeks (all-equal priorities, many ties, spread priorities, and pops on an empty queue).ListPQholds small objects whose<looks at the priority alone, so its scan is FIFO by construction. Count the scripts of each kind and catch everyExceptionas a failure. - Time one script of 5 * 10^4 pushes then 5 * 10^4 pops on
StablePQand onPQ: print both times and the ratio, with no verdict (the ratio moves with the machine's load). - Objects whose
__lt__looks at the priority alone are not FIFO inheapqeither (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 whoseheapqpop order is not (priority, arrival position), and print it beside the FIFO order. Then check thatPQis FIFO on every such list of up to 7 priorities.
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.
- Write
smallest_range(lists)withheapqand 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 theValueErrorfor no lists and for an empty list. - Write the brute force: try every pair of values
(lo, hi)from the input, narrowest first (smallerlofirst 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 everyExceptionas a failure. - 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.
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.
- Write
k_sorted(n, k, rng)(exactlynitems;ValueErrorfor a negativenork),max_displacementandwindow_sort(items, k)(a new list;ValueErrorfork < 0). Print that the property holds on built inputs. - Check
window_sortagainstsorted()on 300 seeded inputs (empty, single, already sorted,k = 0,k >= n, duplicates). Count the cases of each kind and catch everyExceptionas a failure. Show what happens whenkis too small for the input. - At
n = 10^5andk = 10, 100, 1000, count the comparisons ofwindow_sortand ofsorted()(through a counting wrapper, checked equal to the plain results). - 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.
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.
- Write
Revand check that popping a heap ofRev(word)equalssorted(words, reverse=True)on 300 seeded word lists (empty, single, duplicates, sorted and reverse-sorted lists). Count the lists of each kind and catch everyExceptionas a failure. - On
(count, word)pairs from aCounterof seeded word lists, check the(-count, word)heap againstsorted(pairs, key=lambda p: (-p[0], p[1]))on 300 lists, and show on one sample what wrapping the whole pair inRevwould do to the word order. The wrapper's cost in time is measured later in this topic.
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.
- Write
top_k_frequent(items, k)and run it on a word list with ties.k <= 0gives[];kabove the number of distinct items gives all of them. - Check it against the oracle that sorts every
(-count, item)pair on 300 seeded lists (empty, single, ties,k = 0,kabove the distinct count, all equal). Count the cases of each kind and catch everyExceptionas a failure. - 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,
kfrom 1 to 3) and print it beside the truth. Then show thatCounter.most_common(k)leaves ties in first-seen order, like the buggy key (CPython behaviour), on every list of the scan.
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.
- Write
merge_heapify(a, b)andmerge_push(a, b)(each returns a new list and leaves both heaps alone). Check both withis_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 everyExceptionas a failure.is_heap,Key(a value that counts every<) and the listsBED(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. - Count the comparisons of each on random items,
N = 10^4andM = 10, 100, 1,000, 10^4, and print which is cheaper in each case from the counts. - Count them again when every pushed item is a new minimum and they arrive largest first, for
M = 1,000andM = 10^4, and print the winner of each from the counts. - 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.
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.
- Write
HNodeandNodeHeapwithpush,popandpeek(IndexErroron an empty heap), and check it againstheapqon 300 seeded scripts (empty pops, a single item, duplicates, ascending and descending pushes, peeks). Count the scripts of each kind and catch everyExceptionas a failure. Never print a node. - Print the path of slots 1, 2, 3, 5, 6 and 11 from the binary digits.
- Measure bytes per item with
tracemallocfor 3 * 10^4 ints (built first) in aNodeHeapand in aheapqlist. - Time
npushes thennpops onNodeHeapand on the hand-written array heap (sift_up,sift_downandMinHeapare 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 inO(log n), and are named here and not built.
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.
- Write
to_max_heap(a)(in place, returnsNone) and check it withis_max_heapon every min-heap inBED(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 withpop_maxgivessorted(heap, reverse=True).is_heap,is_max_heap,sift_down_maxandBEDare written out in the answer. - 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
Exceptionas a failure. - 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 inBED, and print how often the bound is met exactly. - 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.
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):ValueErrorif the item is already held. O(log n).pop(): remove and return the smallest(priority, item);IndexErroron an empty heap. O(log n).update(item, priority): give a held item a new priority, smaller or larger, and restore the heap.KeyErrorif 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 intopos. Nothing else writesposexceptpush(new entry) andpop(deleted entry). The helperis_heap(a)(true when no slot is smaller than its parent) andbest_of(fn)(the smallest time of 3 runs) are written out in the answer.
- 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. - 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]] == ifor every slot,len(pos) == len(a)andis_heap(a). Count the cases each kind of operation hit,Exceptionas a failure. - 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
heapqlist 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. - One line: the best-known user of decrease-key is Dijkstra's shortest paths (DSA Topic 18). Nothing here walks a network.
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.
- Write
CancelPQonheapqwithpush(item, priority)(pushing an item that is already live replaces it: the old entry is cancelled),cancel(item)(KeyErrorif the item is not live),pop()(the live entry with the smallest priority, the earliest pushed among equals, as(priority, item);IndexErrorwhen nothing is live), andlen()(live items only). Count the stale entries popped and the peak number of entries the heap held. - Check it against a real removal: a
ListPQ(an unsorted list popped by a scan) whosecanceldeletes 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. - 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. - 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.
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).
- Write
DHeap(d), a min-heap withpush,popandpeek;d < 2raisesValueError, an emptypoporpeekraisesIndexError. Writeis_dheap(a, d)and check, ford= 2, 3 and 4 on every list inBED(every order of 0 to 6 distinct items and every list over 0, 1, 2 of up to 6 items), and ford= 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 assorted()gives. - Print the number of levels a heap of 10,000 items has for
d= 2, 3, 4, 8 and 16 (the smallestLwith1 + d + ... + d^(L-1) >= n). - Count comparisons per item for
npushes followed bynpops of random items,n= 10,000, for those fived(aKeywrapper counts every<; the counted run and the timed run share the class, so time plain integers). Print whichdneeded the fewest and which the most, from the counts. - Time
d= 4 againstd= 2 on the same input and print the ratio (ratio only: it moves from run to run). - A student writes the 4-ary
sift_upbut 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 andis_dheapbeside 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.
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.
- Check on 50 seeded inputs with duplicates, plus an empty list, one item, ascending, descending and all-equal lists, every
kfrom -1 ton + 1, that the two calls return the same list. - 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. - For
k = 1, check thatmax(xs)equalsnlargest(1, xs)[0]and print the time ratio (ratio only). - 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 largekand fork = 1print the ratios only, with no recommendation.
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.
- Build runs: draw
Nrandom items first, cut them intoknear-equal chunks (the lengths add up toN) and sort each chunk. Check briefly (the full check ofheapq.mergeagainst sorting was shown earlier in this topic) that the two calls return equal lists fork= 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. - Time both at
N= 100,000 fork= 2, 10, 100 and 1,000 and printmerge time / sorted time: how many times slowermergeis. Give a verdict only fork= 2, and only when the ratio is at least 2; the otherkprint the ratio alone, because their gaps move from run to run on a busy machine. - Count comparisons per item for both at
N= 20,000 and the same fourk. - Count the most items each one holds at once at
N= 20,000: feed the runs tomergethrough generators that count how many items they have given out minus how manymergehas handed on, and note thatsorted()builds a list of allN(the lazy merge earlier in this topic already showed the heap holding at mostkentries; here that is set againstsorted()). (The external sorter of DSA Topic 9 merged runs from temp files for exactly this reason.) - 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.
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.
- Write
median_heapq(xs)(twoheapqheaps),median_hand(xs)(the same two heaps on the hand-writtenMinHeap) andmedian_insort(xs)(insort). Each returns the list of lower medians, one per item. Check all three againstsorted(xs[:i + 1])[i // 2]on 300 seeded lists, with an empty list, one item, ascending, descending, all-equal and duplicates. - Time
median_heapqagainstmedian_insortat 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. - At 10,000 random items (hand-written pops are slow, so not 50,000) time
median_hand,median_heapqandmedian_insortand printinsort / hand-writtenandhand-written / heapq(ratio only: no verdict). - 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.
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.
- Write
LazyMedianwithadd(x),remove(x)(x must be in the window; it marks one copy as delayed, adjusts the live counters and prunes both tops) andmedian(), thensliding_median(a, k)on top of it:ValueErrorfork < 1,[]whenk > len(a). State the time (O(n log n)) and what the heaps can hold. - Check against the
bisectsorted-window version on 300 seeded inputs (empty, one item, ascending, descending, all-equal and many duplicates, withkfrom 1 ton + 1) and count the cases hit. - Print the most entries the two heaps held at once, beside
k, for random, ascending and descending lists of 5,000 items withk= 50. - A student balances by the raw heap sizes
len(low)andlen(high), which still include the delayed items (B57 in the code). Find the smallest input that gives a wrong list, by a scan ofBED(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 overBEDhow many outcomes are wrong and how many of those are an exception.
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.
- 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.ValueErrorfor a repeated id, a length below 1 or a negative arrival. State the time (O(n log n)) and the space. - Print a schedule for eight jobs that has simultaneous arrivals, an idle gap and two jobs with the same priority, and the average wait.
- 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 <= nowinto aListPQ, 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. - 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.
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.
- Write
assign_rooms(meetings)returning(rooms_used, room_of), whereroom_of[i]is the room of the i-th input meeting.ValueErrorif a meeting hasstart >= end. Print the result for eight meetings that include two touching ones, and state the time (O(n log n)) and space. - 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-forceassign_brutethat 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, thatassign_roomsequalsassign_brute, that no room holds two overlapping meetings and that the rooms used are numbered0torooms_used - 1. Count the cases with touching meetings and with equal starts. - 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.
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
tfinishes att + 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.
- Write
run_desk(customers, c)returning(starts, finishes, handled): each customer's start and finish minute and the number of events handled.ValueErrorforc < 1, a service below 1 or an arrival below 0. State the time (O(n log n)) and space forncustomers. - 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.
- Write
run_ticks(customers, c), the tick-by-tick version: for each minutetin turn, append the customers arriving attto the line, then give the front customer to a free clerk (one whose last customer finishes at or beforet) while any clerk is free and anyone waits. It returns the starts and the number of ticks it looped. Check every start time ofrun_deskagainst 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. - 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.
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.
- Write
schedule(tasks, n)(a string of letters in, a string of slots out) on the heap and the deque, andschedule_scan(tasks, n), which follows the same rule by scanning every letter in every slot. Writeis_valid(tasks, n, out): the same copies of each letter astasks, and any two runs of one letter at leastn + 1positions apart. - Print the schedule of
"AAABBB"withn = 2and its length. - 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 thatscheduleis valid, never ends with an idle slot, and equalsschedule_scan. Count the inputs of each kind and catch everyExceptionas a failure. schedule_no_cooldownis the broken version: it puts a letter back into the heap at once and ignoresn. Find by a plain search the smallest failing input (strings overAB, shortest first,nfrom 1 to 2) and print the broken schedule beside the true one.
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.
- Write
k_smallest(a, k, stats=None). Whenstatsis a dict it recordspops,pushesandpeak(the most pairs in the frontier). Check againstsorted(a)[:k]thatais unchanged, pops aremin(k, n)and pushes at most2 * pops + 1, for every heap inBEDand everykfrom -1 tolen(a) + 1, and on 300 seeded heaps built withheapq.heapify. Count the heaps andkvalues of each kind and catch everyExceptionas a failure. - On a heap of 10^5 items count pops, pushes and the frontier's peak for
k= 10, 100 and 1,000, assertpushes <= 2k + 1andpeak <= k + 1, and print them besiden. k_smallest_left_onlyis the broken version: it pushes only the left child. Find by a plain search overBED(shortest first) the smallest failing heap andk, and print what it does beside the truth.
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.
- Write
window_max_heap(a, k)andwindow_max_deque(a, k)and check both against themaxof each window on 300 seeded inputs (empty,k = 1,k = n,k > n, duplicates). Count the inputs of each kind and catch everyExceptionas a failure. - In separate counted copies, count the most entries each holds after a step (
peak) and the pops (heap pops; the deque'spopandpopleft) atn = 10^5andk = 1,000on random, ascending and descending input. Assertdeque peak <= kandheap peak <= n, and that each counted copy returns what the plain one does. - Time the plain functions on the random input for
k = 10andk = 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. window_max_heap_ifis the broken version: anifthat 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.
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.
- Write
running_percentile(stream, p)and check it against sorting each prefix on 300 seeded streams forp= 50, 90, 99 and 100 (empty, single, sorted, reverse-sorted, all equal and duplicates included). Count the streams of each kind and catch everyExceptionas a failure. - Count the pairs
(p, n)withpin 1..99 andnin 1..1,000 wheremath.ceil(p / 100 * n)differs from(p * n + 99) // 100. Print the count and the first pair in order ofp, thenn, withp / 100 * nas Python prints it. running_percentile_flooris the broken version: it usesmax(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.
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.
- 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
sortedby(priority, n). - 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 mostlog2(n)comparisons, a pop at most2 * log2(n). - Time both on plain code (min of 3) and print the ratio of the
Jobtime to the tuple time, with no verdict. - 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.
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).
- Write
skyline(buildings)andskyline_scan(buildings), the brute force: for each edgex, the height is the largestheightamong buildings withleft <= 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 everyExceptionas a failure. - Print the skyline of
[(2, 9, 10), (3, 7, 15), (5, 12, 12), (15, 20, 10), (19, 24, 8)]. skyline_ends_firstis the broken version: at eachxit 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.
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.
- Write
best_team(engineers, k)andbest_team_scan(engineers, k), which tries every team of size 1 tomin(k, n)withitertools.combinations. - 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 everyExceptionas a failure, and print the mismatches. - Print a small example with its best score.
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.
- 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 = 10andc = 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. - Check the static key against
simulate_scan, a brute force that recomputes every waiting job's effective prioritypriority * 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) forcin 1, 3, 10 and 100, and for no aging. Compare the full service order, count the runs where aging changed the order, and catch everyExceptionas a failure. - Close with a sentence built from the printed numbers.
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.
- Write
pop_bottom_up(a): in place on the lista(a min-heap), returning the smallest item,IndexErroron an empty list. Check on every list inBED(heapified first) that popping everything givessortedorder and thatais 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. - On a heap of 10^5 distinct
Keys (a shuffledrange(10**5)), count the comparisons of each of the first 2 * 10^4 pops for the textbookMinHeap.pop,pop_bottom_upandheapq.heappop(heappopis C code that callsKey.__lt__, so its real comparisons are counted), and print the averages beside2 * log2(n). Assert the three pop the same values, that each average is at most2 * floor(log2 n), and thatpop_bottom_upandheappopmake 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.) pop_bottom_up_no_sift_upis the broken version: it leaves out the final sift up. Find by a plain search overBED(shortest first, heaps only) the smallest failing heap and print it beside the truth.- Close from the counts: say whether bottom-up used fewer comparisons than the textbook pop and whether
heappopmatched it on every pop.
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:heapqon a list (heappush,heappop).SortedPQ: a sorted list that stores the negated numbers in ascending order, so the smallest number is at the end;pushisbisect.insort(items, -x)(a binary search, then a shift of the tail: O(n) but one fast C-level memory move) andpopisitems.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.pushwalks down from the root to a free place;popwalks 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). Itsheightcounts 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:mitems start in the structure (random inrange(1000)); thenNtimes: 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 withm = Nitems held. - mixed:
Noperations, each a push of a random number (probability 1/2) or, if the structure is not empty, a pop. - fill, then drain:
N / 2pushes of random numbers, thenN / 2pops.
- 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.
- Time every structure on every workload (plain code, min of 3) and print the times and the ratios
SortedPQ / HeapPQandTreePQ / HeapPQ. Every ratio is printed as a ratio only: a time ratio moves with the machine's load, so no verdict rests on one. - 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
heapqmakes per hold operation (withKey) 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. - After the hold workload with
m = N / 10, printTreePQ.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. - 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).
- 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.
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
2iand2i + 1in sift down. - B71b uses the 1-based parent
i // 2in sift up. - B71c tests the right child with
child + 1 <= n, so it can read one slot past the heap. - B71d loops
while i >= 0in sift up, so slot 0 is compared with slot(0 - 1) // 2 = -1, which is the last item.
- For each bug, find its smallest failing list by scanning
BEDfrom 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. Checkis_heapafter 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. - Run the same check on all of
BEDand sort every failure into "raised", "caught byis_heap" or "seen only in the pop order". Assert that the last group is empty for every bug. - Show why the property check matters. With B71b, count the lists of
BEDwhose pops come out unsorted, then the same over 300 random lists of 100 items. - 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 everyExceptionas a failure, and check that popping an empty heap raisesIndexError. End with the lesson, printed only if the counts support it.
Two student versions of sift_down(a, i, n) look almost right:
- B72a swaps
a[i]with its smaller child but never movesidown 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.
- 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.
- Confirm the predictions by scanning the heaps of
BEDfrom the shortest (the 9,194 lists of every order of0..k-1and every list over0, 1, 2, lengths 0 to 7, keeping those that passis_heap). Pop everything from each heap and report two things per bug: the first heap whose pops leave an array that failsis_heap, and the first heap whose pops come out unsorted, beside the truth. Assert that the first matches your prediction. - 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 anyExceptionas a failure. Run it on both bugs (each must fail some scripts) and on the correctsift_down(no failures, every kind counted).
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.
- Find each one's smallest failing list in
BED(every order of0..k-1and every list over0, 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 correctheapify. Show that both bugs fail first on the same input, for two different reasons. - A failing input that both bugs share cannot tell them apart. Scan
BEDfor 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 ofBEDeach bug fails, and how many both fail. - Check the correct
heapifyon all ofBED, then fuzz it on 300 seeded lists againstsorted(): 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 everyExceptionas a failure.
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.
- 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 nextheappopdiffers from a scan for the smallest(priority, name). Print the heap,is_heapafter the edit, the wrong pop and the right one. Then writereprioritise(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. - 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. - Fuzz
reprioritiseagainst 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 raiseIndexError), and count anyExceptionas 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.
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()insidepush, 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.
- 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.
- Repeat with dict items. Print each bug's smallest failing script with the
TypeErrorand 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. - 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 everyExceptionas a failure.
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.
- Print
nan < 1.0,1.0 < nanandnan == nan. - 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-writtenheapifythen pops,heapq.heapifythen pops, andheappushone 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. - Push the str
"three"onto the heap[3], catch theTypeErrorand print its type and message. Two strs compare fine. - Fix it at the door with
CheckedHeap. Itspushrefuses nan withValueErrorand refuses any key whose type differs from the first one pushed withTypeError, and both happen before any comparison. Fuzz it on 300 seeded float lists againstsorted()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 everyExceptionas a failure, and check that an empty pop raisesIndexError.
DSA Topic 14 met the same keys that break the order in a search tree.
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)islen(high)orlen(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
lowand moves a top tohighonly when the sizes are off. Nothing ever compares the two tops. - B77b moves high's top to
lowwithout negating it.
- For each bug, find the smallest stream in
BED(shortest first) where its medians differ from a sorted list kept withinsort. Print both lists and the first rule broken, with the add that broke it. - Run every list of
BEDas 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. - 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 everyExceptionas 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.
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 readsh[0].
- For every list of
BED(shortest first) and everykfrom -1 to n + 1, compare each bug withsorted(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. - Check the correct
top_kon the same cases. Then fuzz it on 300 seeded lists (empty, single, sorted, reverse-sorted, duplicates, random) withkin -1, 0, 1, a random value, n and n + 1, passing an iterator so it is read only once. Count everyExceptionas a failure.
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 fromlists[i].
- 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. - Check
merge_kon 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 everyExceptionas a failure.
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
posfor 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).
- Run B80a on every valid script of 1 to 4 operations over items
a,band priorities 0 to 2 (push, update, pop), fewest operations first. After every operation, checkis_heap, thatposmatches 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 theposcheck off and print the smallest script whose damage shows anyway. That array still passesis_heap. - 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.
- 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 everyExceptionas a failure. The two bugs must fail some scripts and the two correct versions none.
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
heapifyover 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 byremove(). Each pop scans the whole list withmin(), then again withremove()up to the match; onlymin()'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).
- 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 anyExceptionas a failure. This shows that nothing but the cost is wrong. - 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.
- 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.
- 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. - Print a closing line built from the verdicts.
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).
- Write the correct scheduler, the brute force and both bugs.
- 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. - 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.
- 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
Exceptionas a failure.
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).heapifyworks in place and returnsNone, aslist.sort()does, sohisNone. - B83b:
heapq.heappush(xs, x)on a list that was never heapified.heappushassumes 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 (heapifyand pushing one at a time can disagree), so two correct heaps of the same items can be unequal lists. Compare the pop order, orsorted()of each.
- For each bug write the broken line and the right way.
- Find each bug's smallest failing input by a plain scan, in order of size: for B83a every list over
0, 1, 2of length 0 to 3, for B83b every such list of length 0 to 4 with every pushed value in0, 1, 2, and for B83c every order of0..k-1for k = 0 to 5. Print the failure beside the truth and assert it. - 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 anyExceptionas a failure.
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.
- Write
sift_down_recwith adepthargument 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. - Build a heap of 100,000 random items with the recursive
heapifyand pop every item with the recursivesift_down. Print the deepest depth againstn.bit_length()and againstsys.getrecursionlimit()(as a boolean: is the deepest depth under the limit?). Assert the deepest depth is at mostn.bit_length(). Never print a depth at which a recursion failed, and never change the limit. - Print what 1,000,000 items would need, computed from
bit_lengthand not run, and what a path as tall as the input would need beside the limit, as a boolean. - On 20,000 random items, run both versions through
heapifyand through a full pop-all. They must make the same swaps (counted, asserted) and leave the same arrays. - 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 anyExceptioncounted as a failure.
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.IndexErrorwhen there is no live entry.q.peek()returns the same pair without removing it.IndexErrorwhen 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 returnsTrue; it returnsFalseif 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 qisTrueexactly 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.
- 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 andRefPQside by side and compares every result and observation. The first nine tests are small and aimed: an empty queue'speek, an emptypop,lenafter 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 itemsa,band priorities0,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:peekon a marking queue drops stale entries, which can hide a bug that a run without observations would show. A test that raises anyExceptionis a failure, not a crash; it names the exception. - 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
Falseand a re-push of an item that was served or cancelled. Assert each was hit. - Run the suite on the three correct queues (the hand-written heap,
heapqthroughPQ, and the scan throughListPQ) and assert that every test passes. - Run it on six planted bugs: S1
peekon an empty queue returnsNone; S2lenis not reduced bypop; S3 entries are ordered(item, priority, n); S4cancelmarks the item's name, so a re-pushed item is lost; S5popdoes not skip cancelled entries; S6inis writtenitem in self.base.h(the heap list holds tuples, so it is alwaysFalse). - 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.
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 nextseq.ValueErrorif the item is already held.pop(): remove and return(item, priority)with the smallest priority, and among equal priorities the one pushed earliest (smallestseq).IndexErrorwhen the queue is empty.peek(): the same pair, left in place.IndexErrorwhen empty.update(item, priority): give the held item a new priority, smaller or larger. The entry keeps itsseq, so among equal priorities it keeps its place in line (updating an item to the priority it already has changes nothing).KeyErrorif 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.KeyErrorif it is not held.item in pqisTrueexactly when the item is held, andlen(pq)is the number held (__contains__and__len__).- Every operation is O(log n) except that
peek,lenandinare O(1). Every move of an entry goes through one helper_swap(i, j), which exchanges two slots and writes both new positions intopos; nothing else writesposexceptpush(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 <).
- Write
UpdatablePQand check the contract on a short trace, including three items with equal priorities and aTokenclass (hashable, with no<) to show that items are never compared. - Check it against
ModelPQon 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 thatpos[a[i][2]] == ifor every slot, thatlen(pos) == len(a), thatis_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 anyExceptionas a failure. - 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.
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 atnow + delay. Returns its timer id: 0 for the first call, then 1, 2, and so on.ValueErrorifdelay < 0. A timer withdelay == 0is due now and fires on the nextadvance.cancel(timer_id): returnsTrueif the timer is pending (scheduled, not yet fired, not cancelled) and cancels it;Falseotherwise (already fired, already cancelled or never issued).advance(new_now): moves the clock tonew_nowand fires every pending timer withdue <= new_now, in (due time, id) order. Returns the list of their names.ValueErrorifnew_now < now.next_due(): the due time of the earliest pending timer, orNoneif 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 andheap_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).
- Write
TimerService,TimerListand the driver. - Run one seeded workload and print every compaction: the heap size before and after. After a compaction the heap size must equal
pending(). - Check the service against
TimerListon 300 seeded scripts, comparing every return value (or exception name) andpending(), 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 returnedFalsefor each of its three reasons,ValueErrors, compactions) and count anyExceptionas a failure.
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,
nsmallestat query time. A dictscoresfrom name to score;top(k)callsheapq.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.addpushes 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 firstkvalid ones, then pushes thosekback, 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.
- Write both boards. Check both against the oracle on 300 seeded scripts of
addandtopover 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 negativek, aklarger than the number of players, equal scores in the answer) and count anyExceptionas a failure. - Time the two designs on the plain code on an update-heavy workload (many
adds, few queries) and a query-heavy one (fewadds, 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. - 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).
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.
- Build four seeded files of 2,000 lines each, sources
web,db,cacheandauth, withdbat mostd = 3places late (shuffle blocks ofd + 1consecutive lines of a sorted file, and assertmax_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. - 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 thedbfile. Assert that the first N lines equal the oracle:sorted()of all the lines in file order by timestamp (stable). - 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
Exceptionas a failure.
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.
- Write
simulate(procs, q, c)with aheapqheap of(key, seq, pid), and the brute forcesimulate_scanwhich 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 byseq, the idle jumps and the requeues). - Print a table of one small workload of six processes with
q = 2andc = 3: pid, arrival, burst, priority, finish, turnaround and wait. - Check both against each other on 300 seeded workloads (0 to 12 processes,
qfrom 1 to 4,cfromNone, 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 byseq, a requeue) and count anyExceptionas a failure. - 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 withc = 25. Build the closing line from those numbers.
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) andk(an int, at least 0) are fixed once; anything else raisesValueError.add(x)raisesTypeErrorwhenxis not an int. - Queries over the
mitems now in the window, withsthe window sorted ascending:minimum()andmaximum():s[0]ands[-1].median(): the lower median, the item of 1-based rank(m + 1) // 2(index(m - 1) // 2ofs).percentile(): the nearest-rankp-th percentile, the item of 1-based rank(p * m + 99) // 100, computed in integers (sop = 100is the maximum).top(): theklargest window items, largest first, repeats kept: allmof them whenm < k,[]whenk == 0.- Before any item has arrived the window is empty: the first four return
Noneandtop()returns[].
- Equal values are interchangeable, so ties need no rule for the answers; inside the heaps every item is the key
(value, seq), whereseqcounts 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.
- Write
StreamStatswithadd, the five queries and the rebuild. State each method's time and space withWandknamed, and argue why the rebuild keepsaddat O(log W) amortised. - Show the contract (each bad argument, the empty window, a float) and trace
W = 4,p = 75,k = 2on5, 1, 4, 1, 9, 2, 6, checking each row against sorting the window. - 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 > Wandp = 100among them. Count each case hit, and catch everyExceptionas a failure. - 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.
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.
ValueErrorform < 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.
- Write
print_farm(m, jobs)returning{id: (printer, start, end)}, with its time and space (njobs,mprinters). - 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.
- 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
Exceptionas a failure. - 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).
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 totime, then adds the message unread.ValueErrorfor an id used before or a time before the clock.top(k): the ids of thekbest visible unread messages, best first; all of them when fewer;[]whenk <= 0.mark_read(id):Trueif it was unread (visible or snoozed),Falseif already read;KeyErrorfor an unknown id.snooze(id, until): hides an unread message until the clock reachesuntil, which must be later than now (ValueErrorotherwise); a second snooze replaces the first;Falsefor a read message;KeyErrorfor an unknown id.advance(now): moves the clock (ValueErrorif it goes back); every snoozed message withuntil <= nowbecomes 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.
- Write
Inboxand state each method's time and space (nentries held,k,sstale entries skipped,wwake entries). - Trace a short morning: four messages, a snooze, reading a message twice,
topwithk = 0andklarger than the inbox, a message waking exactly at itsuntil, and each error. - 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 (emptytop,kabove the visible count,k <= 0, reading a read or a snoozed message, snoozing a snoozed one, waking exactly atuntil, importance ties in an answer, each error) and catch everyExceptionas a failure. Print the stale entries skipped and the most entries held against the most unread messages.
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.
ValueErrorforF < 1, a negative time or a floor outside0..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.
- Write
elevator(F, requests)returning(total floors travelled, waits in input order), with its time and space forrrequests. - Print a morning in a 10-floor building: each request's wait, the travel, the average and the longest wait.
- 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,
Ffrom 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 everyExceptionas a failure. - 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).
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. ValueErrorfor an id used before, a side other than"B"or"S", or a price or quantity below 1.cancel(id)returnsTrueif the order was resting and removes it,Falsefor 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.
- Write
Enginewithsubmit,cancelandbook()(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). - 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.
- 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 everyExceptionas a failure. Print the stale entries skipped and the most heap entries against the most live orders, and assert the bound the rebuild gives.
"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").
- The property and the layout: a complete binary tree stored in a list, every parent at most its children, parent
(i - 1) // 2and children2i + 1,2i + 2; a heap is not a sorted list. - 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). - 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. heapqand negation for a max-heap; whether this Python has public max-heap functions, printed withhasattr.- The stable priority queue: why
(priority, item)breaks on equal priorities with dict items, and how a counter fixes it and keeps arrival order. - Top-k with
nlargestagainstsorted(), and two heaps for a running median. - When a heap buys nothing over
sorted(): you need every item in order,kis nearn, or the input is already sorted. Let the counts say which of thesesorted()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.
"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 parenti < len(a) // 2it checksa[2i + 1]anda[2i + 2]. - D2
heapify_d2(a): callssift_upon every slot from the last back to 1. - D3
kth_largest_d3(xs, k): returnsheapq.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.
- Write down your predictions and the reasoning (in comments).
- 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 everykfrom 1 ton), D4 over tuples of 1 to 3 ascending lists over with up to 3 items in all, D5 over the heaps inBED. 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. - Give the fix for each in one line.
The helpers is_heap, sift_up and the BED lists are written out in the answer.
"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.
- 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. - 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 everyExceptionas a failure. - Argue "amortised O(log n)" from counts, not by assertion: on 50,000 inserts with pops (ascending inserts with
pop_minevery 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.) - 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).
"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.
- First answer: gather every post and sort, O(P log P) for
Pposts. 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) forkusers. Write both and trace a feed of four users (one with no posts, equal times across users). - 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 everyExceptionas a failure. - Follow-up: "one user has 100,000 posts" and "you follow 1,000 people." Count the posts each page touches against
P. - 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.
"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
durationminutes and is free again atdispatch 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 = 0is allowed: no call is ever dispatched, and each ends "never dispatched". An empty day gives an empty report.ValueErrorforu < 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.
- 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. Withcheckon, after every minute assert that both queues passis_heapand that every waiting call has exactly one valid board entry and nothing else does. State the time and space (ccalls,hchanges), with the checks off and with them on. - 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.
- 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
PQandStablePQ, 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 everyExceptionas a failure. - Run one busy day (10,000 calls, 2,000 changes, 6 units) on
PQand onStablePQ, checks off: time the whole day, and the day's queue pushes and pops replayed alone, and printhand-written / heapqfor 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. - 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.