Queues & Deques: 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 queue serves items in arrival order: first in, first out (FIFO). You enqueue at the back, dequeue from the front, and you can peek at the front, ask is_empty() and take len. Think of a print queue, a ticket line, or the frontier of a search.
Build ListQueue on a plain list (append to enqueue, pop(0) to dequeue) with enqueue, dequeue, peek, is_empty and __len__. Dequeue and peek on an empty queue raise IndexError. Count moves, the references that pop(0) shifts one slot left. Run the same ten operations through the queue and through a list used as a stack (DSA Topic 10, append and pop), and print both output orders side by side. Then show the two errors, and state the complexity of each operation.
DSA Topic 1 timed a pop(0) drain and found it quadratic. Here the cause is counted. pop(0) on a list of length m shifts the m - 1 references behind the front one slot left, so draining n items does n(n - 1) / 2 moves.
Use a ListQueue with a moves counter and print the exact drain counts for n = 10, 100, 1000, 10000, asserting the formula. Then measure what the drain does not show, the steady state: a queue held at length m with one enqueue and one dequeue per step, for m = 10, 1000, 10000, 100000 and 2,000 steps each. Print moves per step beside the time per step (min of 3, each run on a freshly built queue). Hypothesis to test: the cost per operation follows the queue's length, not the number of operations, so it is nearly flat for small m and grows for large m. Word the conclusion from your printed numbers.
DSA Topic 5 kept a list plus a head index, and its rate limiter (Q88) compacted the dead prefix once head passed half. As a queue, dequeue reads items[head] and advances head: O(1), no moves. The cost moves to memory, because the dead prefix items[:head] keeps every dequeued item alive.
Write HeadQueue(compact) with enqueue, dequeue, peek and __len__. With compact=False, run 10^5 steps of enqueue-then-dequeue on a queue that never holds more than 50 items, and print len(items) against the live count and sys.getsizeof of the list. With compact=True, delete the dead prefix whenever head passes half the list. Count copies (items kept by each compaction). On 10^5 seeded random operations, check that copies <= dequeues (amortised O(1)) and that len(items) <= 2 * live after every operation.
DSA Topic 2 built a fixed ring with a start index and a count. This one keeps two indices instead: head, the slot of the front item, and tail, the next free slot. Each moves forward with (i + 1) % len(slots).
With only head and tail, head == tail could mean empty or full. This version settles it by wasting one slot: a queue of capacity c uses c + 1 slots, empty is head == tail, full is (tail + 1) % len(slots) == head, and the length is (tail - head) % len(slots).
Write RingQueue(capacity) with enqueue, dequeue, peek, is_empty, is_full and __len__; enqueue on a full ring raises IndexError. Print a trace of 12 operations on capacity 2 (three slots) that wraps tail around twice, showing the raw slots, head and tail. Fuzz it against a list model on 1,000 seeded sequences. State the cost of each operation.
A ring with a head and a tail has one problem: head == tail looks the same when the ring is empty and when it is full. There are three honest fixes: keep a count (DSA Topic 2's choice), waste one slot, or keep a full flag.
Write all three as CountRing, WasteRing and FlagRing (same methods: enqueue, dequeue, __len__, is_empty, is_full), and fuzz them against a list model of capacity c on 1,000 seeded sequences with capacities 1 to 4, so full and empty are hit constantly. Then write BrokenRing, which uses only head == tail for empty and measures length as (tail - head) % capacity. Using itertools.product, find the shortest operation sequence on which it disagrees with the model and print both logs. Finish with the trade in memory: slots and fields per version.
DSA Topic 2's ring had a fixed capacity and left the growable version for this topic. Write RingQueue (a head, a size and a list of slots) that, when an enqueue finds it full, allocates twice the slots and copies the items in queue order, starting from head and wrapping around, so the new ring starts at slot 0 with head = 0.
Print the raw slots before and after a resize that happens while the ring is wrapped. Then count the copies over n = 10000 enqueues starting from capacity 1, and check the total stays below 2 * n (the doubling argument from DSA Topic 1), so enqueue is O(1) amortised but O(n) for the call that resizes. Fuzz it against a list model from size 0.
A ring that only grows keeps its peak memory forever. DSA Topic 2's dynamic array shrank at a quarter and showed the 50% thrash, so this question confirms that on a ring and spends its effort on what Topic 2 lacked: shrinking a wrapped ring, and a written proof of the copy bound. The obvious fix, halve the capacity when the ring falls to half full, thrashes: sitting right at the boundary, alternating enqueue and dequeue resizes on every operation, and each resize copies every item. Halving when the ring falls to a quarter full leaves it half full after each shrink, so many operations separate two resizes.
Write RingQueue(policy) with policy "half" or "quarter", a minimum capacity of 4, and a moves counter. Build it to 64 items, dequeue down to 32, then alternate 100 enqueue/dequeue pairs and print the resizes and copies for both policies (a confirmation). Then print the raw slots of a quarter-policy ring just before and just after a shrink that happens while the ring is wrapped. Finally run 10^4 seeded random operations on each, checking values against a list model and that the quarter policy's moves <= 2 * operations + 8. In a comment, prove why 2 per operation is the bound.
Make the ring work at both ends. Write RingDeque, a growable ring with push_front, push_back, pop_front, pop_back, peek_front, peek_back and __len__. push_front moves head backward with (head - 1) % len(slots) (Python's % never returns a negative number, DSA Topic 2), and pop_back finds the last item at (head + size - 1) % len(slots). When the ring is full it doubles, copying the items in order from head so the new ring starts at slot 0. An empty pop or peek raises IndexError.
Print a trace of 10 operations that wrap at the front, showing raw slots, head and size. Fuzz it against a list model (insert(0, x), append, pop(0), pop()) on 1,000 seeded sequences from size 0, comparing exception types. State the cost of every end operation. These are the end operations collections.deque provides; CPython lays it out differently, as linked blocks, shown when deque arrives.
The i-th item of a ring is slots[(head + i) % len(slots)]: random access with no shifting. DSA Topic 2's RingBuffer already wrote __getitem__ with negative indices, __iter__ and __repr__ for a ring that only pushes at the back, so those are not the point here. Add the same special methods to RingDeque (a growable double-ended ring with push_back, push_front, pop_front) and test what is new: indexing after push_front moves head backward across slot 0, and after a resize.
Show a wrong version that forgets the % (slots[head + i]) and print what it does after the ring has wrapped. Then run 500 seeded operations and check every valid index, both out-of-range indices and the iteration order against a list after each one.
C ring buffers often force the capacity to be a power of two, because then i % cap equals i & (cap - 1) and the machine skips a division. Show that the two agree for every i in range(-64, 64) at cap = 16 (Python's & on negative integers behaves as two's complement with infinite sign bits, so negatives agree too), and that they disagree at cap = 12, printing the first mismatches. Show that doubling a power of two gives a power of two, using the test c & (c - 1) == 0.
Then measure, with min of 3, one million index computations each way. Hypothesis: in Python the mask buys little, because each operation is dominated by interpreter overhead. Print the ratio, but give no clock verdict: a one-operator difference is swamped by interpreter overhead, and the ratio moves with machine load.
Everything built by hand so far (a list with pop(0), a list plus a head index that only moves forward, and the ring) exists in C as collections.deque (a "double-ended queue", said "deck"). From here on it is the default queue.
-
Show the operations on a small deque.
appendandpopleftmake a queue,appendandpopmake a stack,appendleftadds at the front,d[0]andd[-1]peek at the ends, andlen(d), truthiness andextendwork as for a list. -
Race three ways to drain
nitems (thepop(0)drain was timed in DSA Topics 1 and 2 and in the first questions of this topic): aHeadQueue(list plus a head index), a fixedRingQueue(head and size, the count version of the ring: unlike the head-and-tail ring it wastes no slot) anddeque.popleft. Usen = 10000, 20000, 40000, 80000, build each queue in asetup(outside the timed region), take the best of 3, and print the ratio of each to the deque. Write the conclusion from those same numbers: by how much does the deque lead each hand-written queue? How does the hand-written ring compare with the head index (print the ratio, and give the reason a hand-written dequeue costs more per call than the deque, without a clock verdict on that gap)? Name when you would still write your own queue.
A deque is built for its ends. Build a table of operations, list against deque, at n = 10**4 and n = 10**5: append, pop, front insert (insert(0, x) against appendleft), front remove (pop(0) against popleft), reading the ends, reading the middle (seq[n // 2]), x in seq and len. Print nanoseconds per operation (use more repetitions for the cheap operations) and the growth from 10**4 to 10**5. Hypothesis to test: deque indexing in the middle is O(n), so it grows with n, while list indexing stays flat, and the front operations go the other way. State the rule from the printed numbers.
deque(maxlen=k) keeps only the last k items. Show and print: append on a full one silently drops the front item, appendleft on a full one drops the back item, insert into a full bounded deque raises IndexError (print the exception's type name), and maxlen is fixed at creation and readable as d.maxlen (assigning to it fails; print the type name).
Then use it twice. tail(lines, k) returns the last k lines of an iterable of lines, using memory O(k): run it on a generator of 10**5 generated lines and compare the tracemalloc peak with list(lines)[-k:]. And last_readings keeps the last 5 sensor readings and reports their minimum after each of 8 readings.
DSA Topic 2's ring-buffer MovingAverage already did this in O(1) per add with a fixed array. Rebuild it on deque(maxlen=k), which drops the oldest item by itself when a new one arrives on a full deque. That convenience hides a trap: a running total must lose the dropped value, and the deque never tells you which one it was.
Write class MovingAverage(k) with add(x) returning the average of the last k values (or of all values so far while fewer than k have arrived). Keep window = deque(maxlen=k) and a running integer total. Also write BrokenAverage, which appends first and never subtracts the silently dropped front item. Trace both on k = 3 with 10, 20, 30, 40 (print the window after each add) and show that the broken one prints 33.33 where the truth is 30.00. Then run the correct one over a generator of 10**5 values that is never stored, check it against sum(slice) / len(slice) on the first 2,000 values, and handle k = 0 by raising ValueError.
d.rotate(k) moves k items from the back to the front when k > 0, and from the front to the back when k < 0. Trace it on deque(range(7)) for k = 2, -3 and 9 (more than the length). Compare with DSA Topic 2's rotation by slicing, which builds a new list in O(n). Show rotate(-1) as the way to send the front item to the back of the line, and rotate(0) and an empty deque as edge cases.
Then measure: the hypothesis is that rotate(1) costs about the same on a 10**6-item deque as on a 10-item one, while rotate(k) grows with k. Print the times and state what the numbers show.
n people stand in a circle and every k-th person leaves, counting from the front. Simulate with a deque: rotate(-(k - 1)) moves the k - 1 people before the victim to the back, then popleft removes the victim. Write josephus_order(n, k) returning the elimination order (people numbered 1..n), and survivor(n, k). Print the elimination order for n = 7, k = 3, and the survivor for n = 1..12 at k = 2. Handle n = 0 and check against a list-and-index simulation (idx = (idx + k - 1) % len). State the cost; a faster formula comes later in this topic.
The palindrome check is old: DSA Topic 4 Q20 did it with O(1)-space pointers and DSA Topic 8 Q13 did it recursively. Here you measure what a deque version costs against Topic 4's.
-
Write
is_palindrome_deque(text): load the characters into adeque(lowercased, keeping onlystr.isalnumcharacters; inputs are ASCII), then pop from both ends and compare until fewer than two remain. Test it on ten phrases, including the empty string, one character and punctuation only, and check againsts == s[::-1]on the cleaned text. -
Write
is_palindrome_pointers(text), Topic 4's in-place version: two indices that skip non-alphanumeric characters and compare in place. Check that it agrees with the deque version on the same ten phrases. -
Build a phrase of 10^6 letters (a palindrome with a space after every tenth letter, 1.1 x 10^6 characters) and run both on it. Print each version's
tracemallocpeak in KB, measured in its own run, and each version's best-of-3 time, measured in separate runs withouttracemalloc. Conclude from the printed peaks (the pointers use a tiny fraction of the deque's memory) and say when the deque is still the natural tool: when items are added and removed at its ends while the program runs (a FIFO task queue, a sliding window), whereas for a string you can index, Topic 4's in-place pointers are the better tool. Give no clock verdict.
DSA Topic 1 named this example. Build TwoStackQueue from two lists used as stacks (DSA Topic 10): enqueue pushes onto inbox; dequeue pops from outbox, and only when outbox is empty does it move all of inbox across, which reverses the items into arrival order. Add a moves counter, peek and __len__.
-
Trace 10 operations, printing both stacks after each.
-
Explain why the order is right (reversing twice restores arrival order, and a transfer happens only when
outboxis empty, so no newer item gets ahead of an older one) and why it is cheap (each item is pushed once, moved once and popped once). -
Count moves on seeded operation sequences, print the maximum moves in any single operation, and check that the total never exceeds the number of enqueues. Fuzz against
collections.deque, starting from the empty queue.
Reverse the first k items of a queue and keep the rest in order, using only queue operations (popleft, append) and a stack (DSA Topic 10): dequeue k items onto a stack, push them back onto the queue (the stack reverses them), then move the other n - k items from the front to the back. Write reverse_first_k(q, k) that changes a deque in place and returns None. Print each phase for k = 3 on 7 items, show the edge cases k = 0 and k = n, and raise ValueError for k > n or k < 0. Fuzz against slicing from length 0.
A grid is a list of equal-length strings: . open, # wall, S start, E end. Write shortest_steps(grid) returning (steps, dist): the fewest moves from S to E going up, down, left or right (-1 if E is unreachable) and a dict {(row, col): distance} of every cell reached. A deque is the frontier; mark a cell visited, with its distance, when it is enqueued.
-
Print the distance grid (width 3 per cell,
#for walls,.for unreachable) and the answer, for one reachable and one unreachable grid. -
Explain in comments why it works: cells leave the queue in order of distance, every cell at distance
dbefore any atd + 1, so the first timeEis reached is the shortest. -
Check against a frontier-set expansion (the cells reachable in
dsteps, ford = 0, 1, 2, ...) on seeded random grids. The full treatment on any graph is DSA Topic 17; here only grids.
The same grid search can run one layer at a time: at the start of a layer read len(frontier) and dequeue exactly that many cells; everything enqueued meanwhile belongs to the next layer. Write bfs_layers(grid) returning a list of layers (each a list of (row, col) cells, layer d holding the cells exactly d steps from S). Grids are lists of strings (. open, # wall, S start), neighbours in the order up, down, left, right, and a cell is marked visited when it is enqueued. An empty grid or one without an S raises ValueError.
Print every layer for a small grid. Then check against a version that stores a distance per cell: every cell in layer d must have distance d, and both versions must reach the same cells, on 1,000 seeded random grids. Say in a comment why the layer counter replaces the per-cell distance. Full treatment on any graph is DSA Topic 17.
Processes (name, burst) all arrive at tick 0, where a name is one letter and a tick is one unit of time. Write round_robin(procs, quantum) with a deque as the ready queue: take the front process, run it for min(quantum, remaining) ticks, and if it is not finished put it at the back. Return (timeline, completion, slices): a string with one letter per tick, a dict of completion ticks, and the number of times a process was taken from the queue. quantum < 1 raises ValueError, and no processes gives an empty timeline.
-
For
[("A", 8), ("B", 2), ("C", 4), ("D", 1)]with quantum 2, print the timeline and each process's completion and waiting time (waiting = completion - burst). -
Write
fcfs(procs)(first come, first served, no time slices) and print the same table. Show the waiting time of the short jobB, queued behind the long jobA, under both policies. -
Check on 500 seeded workloads (starting at zero processes) that each letter appears exactly
bursttimes in the timeline, thatslicesequals the sum ofceil(burst / quantum), and state the cost in a comment.
A queue with a size limit must decide what happens to an item that arrives when it is full. Write BoundedQueue(capacity, policy) over a deque, with offer(x) returning whether the caller should believe the item was taken, poll() removing the front (IndexError when empty) and __len__. Three policies: "reject" refuses the new item (offer returns False), "drop_newest" discards it silently (offer returns True, a lie of omission), and "drop_oldest" evicts the front to make room (what deque(maxlen=...) does). The queue counts dropped items itself. capacity < 1 or an unknown policy raises ValueError.
Feed a burst of 20 items (0..19) into capacity 5 with no consumer, once per policy, and print what each policy kept, how many offer calls answered True, and how many items were dropped. Check drop_oldest against deque(range(20), maxlen=5). Say in a comment which kind of data suits which policy. All operations are O(1).
Simulate in integer ticks. Within a tick the order is fixed: (1) arrivals join the queue (an arrival that finds it full is dropped), (2) the consumer removes up to c items, (3) the queue length is sampled. Identical items are modelled by a count. Write simulate(arrivals, c, bound) returning (lengths, dropped), where bound=None means unbounded.
-
Producer
p = 5per tick, consumerc = 3, for 20 ticks: print the sampled lengths unbounded and with a bound of 10. Printp = 2,c = 3too. -
a bursty producer from
random.Random(11)sends 0 or 6 items per tick (average 3) for 5,000 ticks againstc = 3. Print dropped items and the fraction dropped for bounds 2, 5, 10, 20 and for a steady producer of exactly 3 per tick (bound 3). -
The hypothesis is that a bounded queue drops items even though the average rates match, and fewer as the bound grows. Assert it from the numbers and word the conclusion from them. Counted items carry the point; no clock is involved.
Ten situations, six containers: a plain list (a stack from DSA Topic 10, or a queue that never holds more than a few items), collections.deque (a queue, or work at both ends), deque(maxlen=k) (the last k items), a hand-written ring (fixed memory, O(1) indexing, or a language without a deque), two stacks (only stacks available), and a priority queue (urgency order; DSA Topic 15, named only here).
Write choose(**needs) that applies the rules in a fixed order and returns (container, deciding_property). Run it on the ten situations below, print a table, and assert each against the expected container.
- Undo history with no limit
- Print spooler, first come first served
- The last 50 lines of a log
- a work queue that never holds more than 3 items
- a sliding-window maximum helper that adds and removes at both ends
- An embedded sensor buffer, 256 readings, no allocation allowed
- a hospital triage list, most urgent first
- a queue in a language that only offers stacks
- a replay buffer needing
buf[i]in O(1) - Browser history back-button
A queue built from two stacks (inbox takes enqueues; outbox serves dequeues; when outbox is empty a dequeue first moves all of inbox across) is O(1) amortised. Prove it with a potential. Count cost as every push and every pop on either stack. Let Phi = 2 * len(inbox). Then:
- enqueue: cost 1,
Phirises by 2, amortised cost 3; - dequeue with no transfer: cost 1,
Phiunchanged, amortised cost 1; - dequeue that moves
mitems: cost2m + 1,Phifalls by2m, amortised cost 1.
Implement a CountingQueue that tallies cost this way. Check on 1,000 seeded operation sequences (starting at length 0, with dequeue on empty counted as an IndexError, not a cost) that cost + change in Phi <= 3 for every single operation, that the running total cost is <= 3 * operations at every step, and print the amortised cost seen for each kind of operation. Give the same bound as an accounting story: each enqueue prepays two tokens for its later move, and the token balance equals Phi and never goes negative. Finally run the adversarial sequence (n enqueues then one dequeue) and show that one operation costs 2n + 1 while the bound still holds. Amortised is a guarantee for every sequence, not an average over random ones.
Build a stack using only queue operations. Write a small class QueueOnly over a deque that exposes nothing but enqueue, dequeue, peek and __len__ (plus is_empty), so removing from the back is impossible. Then write three stacks, each with push, pop, top, __len__ and a moves counter (every item taken out of one queue and put into another counts 1). Popping an empty stack raises IndexError.
-
PushCostly(two queues): push enqueues the new item into the empty queue, moves every older item behind it, then swaps the two queue names; pop is one dequeue. -
PopCostly(two queues): push is one enqueue; pop moves all but the last item to the other queue, returns the last, and swaps the names. -
OneQueue: push enqueues, then rotates the older items (dequeue, enqueue) behind the new one. -
Fuzz all three against a list used as a stack on 1,000 seeded sequences of push, pop and top (starting at length 0), comparing values and exception types.
-
Count the moves. Build n = 300 items, reset
moves, then alternate push and pop 50 times and print moves per push+pop pair for each version. Print the moves of building n items, and of draining them. There is no amortised rescue: say why, and say why nobody ships this (a list is already an O(1) stack).
DSA Topic 10 built undo and redo with two stacks. A real editor keeps only the last k edits, so when the undo stack is full the oldest edit, at its bottom, must go. On a list that is pop(0), O(k); a deque(maxlen=k) used as a stack drops it in O(1) by itself. DSA Topic 10 capped a browser history on a list by trimming in batches (O(1) amortised); deque(maxlen=k) gives O(1) in the worst case, per edit, with no batching.
Write History(k) over a text buffer with type(s) (append text), erase(n) (delete up to n characters from the end; erasing nothing records nothing), undo() and redo() (each returns True if it did something). A new edit clears the redo stack. Store each edit as ("add", s) or ("del", removed_text). Print the buffer after each of 12 operations with k = 3. Then check against an oracle that keeps unlimited history plus a floor index (undo is allowed only above the floor, which rises to len(done) - k after every new edit), on 1,000 seeded operation sequences with k from 1 to 4 and sequences starting at length 0.
DSA Topic 5 Q22 already wrote window_maxima with a list and a head index, fuzzed it and gave the amortised argument. Topic 5 also timed it against the O(nk) scan, so none of that is repeated here. What a real collections.deque changes is memory, and the input no longer has to be stored. Write window_max(items, k, stats=None), where items is any iterable, so the deque holds (index, value) pairs rather than indices into a list. The pairs' values strictly decrease from front to back. Each new item pops every back pair whose value is <= its own, the front is dropped once its index leaves the window, and the front's value is the answer. k < 1 raises ValueError; a k larger than the input gives []. If stats is given, record the maximum deque length and the number of appends and pops. Build it on a generator iter_window_max that yields one maximum at a time, and let window_max be list(...) of it.
-
State the invariant as a comment before the loop, and the O(n) argument after it (each item is appended once and popped at most once, so the scan is O(n) for every
k). -
Fuzz it briefly against Topic 5's list-plus-head version (rewrite it in a few lines over the same pairs), for lengths 0 to 2,000 and several
k, starting at length 0. Also check one case againstmaxof each slice. -
Run
iter_window_maxon a generator of 300,000 values (strictly decreasing,k = 100) that is never stored, consuming the output without keeping it. Print thetracemallocpeak beside the list-plus-head version run the same way, whose list grows to n. -
Topic 5 already measured this against the O(nk) scan; not repeated. Print one line saying so.
The mirror image of the window maximum: window_min(items, k, strict=False, stats=None) keeps indices whose values increase front to back. The back pops while its value is >= the new one (strict=False) or only while it is > the new one (strict=True). Both give the right minimum values, but they do not hold the same candidates: with >, equal values pile up. Record the longest the deque ever gets. k < 1 raises ValueError.
-
Fuzz both rules against
minof each slice (lengths from 0, severalk, values with many duplicates). -
On n = 5,000 with k = 50, print the longest deque for both rules on three inputs: all equal, random values from 0 to 10^6, and few distinct values (0 to 2). Assert what the structure forces on the all-equal input and print the others without a prediction.
-
DSA Topic 5 broke ties for the window maximum's index with a rightmost-wins rule (pop on
<=) and already showed that the values agree; mirror it for the minimum. Say which rule matches "the rightmost index of the minimum" and which "the leftmost", and what each costs in space. State the O(n) argument as a comment.
Build MaxQueue with enqueue(x), dequeue(), max() and __len__, all O(1) amortised. Keep the items in one collections.deque, and a second deque of candidate maxima, by value, in non-increasing order from front to back. This is the queue counterpart of DSA Topic 10's min-stack.
-
enqueuepops the candidates' back while it is strictly smaller than the new value, then appends. Equal values stay, becausedequeueidentifies the leaving item by value.dequeueremoves the front item, and the front candidate too if it equals that item. EmptydequeueandmaxraiseIndexError. -
Show why equal values must stay. A
BrokenMaxQueuethat pops while<=loses a duplicate: print its wrong answer beside the truth, using the input[3, 3, 1]and one dequeue. -
Fuzz both against
maxof a plain list model on 2,000 seeded operation sequences (starting from the empty queue) with values drawn from 0..4, so duplicates are everywhere. Compare every return value and exception type. The correct queue must fail none; the broken one must fail some.
A second route to a queue with O(1) max: a queue built from two lists used as stacks (stacks are DSA Topic 10): enqueue pushes onto inbox; dequeue pops from outbox, and only when outbox is empty does it first pop every item off inbox and push it onto outbox, which reverses them so the oldest is on top. The stacks hold (value, max so far) pairs, as in DSA Topic 10's min-stack. Build TwoStackMaxQueue with enqueue, dequeue, max, __len__ and an ops counter that counts every push and pop on either stack.
-
In
inbox, the pair's max covers everything at and below it. Inoutbox, a transfer rebuilds the maxima as it moves each item across (the top ofoutboxis the oldest item, and its max covers everything below it). The queue's max is the larger of the two top maxima; an empty stack contributes nothing. EmptydequeueandmaxraiseIndexError. -
Write
window_max_stacks(items, k)(enqueue each item, dequeue once the queue holds more thank, read the max oncekitems have arrived) andwindow_max_deque(items, k)(the monotonic deque, indices, back pops while<=). Both return(result, ops). Fuzz both against the max of each slice, starting at size 0. -
Compare counted pushes and pops on
n = 10^5,k = 100for a random input and a decreasing input, with the times and their ratio printed beside the counts; give a clock direction only where the time ratio is at least 2x. State what this structure gains over the monotonic deque: the stacks never discard a value by comparing it, so any associative operation works if you combineoutbox's aggregate beforeinbox's; the deque relies on a larger later value making earlier ones useless.
For every window of size k, report the first negative number in it, or 0 if there is none. Write first_negative(items, k) with a deque of the indices of the negatives: append each negative's index, drop the front once it leaves the window (one index can leave per step), and the front is the answer. Handle len(items) < k (empty result) and raise ValueError for k < 1. Print the result for a short list, check that the deque never holds more than k indices, and fuzz against a scan of each slice, starting at size 0.
DSA Topic 5 found the longest run of 1s with one 0 flipped, on a stream, by remembering only the last zero, and noted that k flips need the last k zeros. Here they are. Write longest_ones(bits, k) for any iterable of 0/1 values (it is read once and never stored): a deque holds the positions of the zeros in the current window; when a new zero makes k + 1, the window's left edge moves to just past popleft(). Return (best, count, peak): the longest window, how many values were read, and the largest deque length seen. Run it on a generator of 200,000 seeded bits, and fuzz against a list-based window scan on 1,000 seeded lists (sizes from 0, k from 0).
DSA Topic 7 answered "is there a repeat within distance k?" with a dict of last positions (memory grows with the number of distinct values) and named the eviction queue for here. Write repeat_within(items, k): keep a set of the last k items and a deque of the same items in order. Test membership first, add the new item to both, and when the deque holds more than k, remove its front from the set too. It returns (found, scanned, peak) where peak is the largest set size. Because it returns at the first repeat, the window holds distinct items and the removal is safe. Run it on a generator of 100,000 distinct values (so it scans everything), and fuzz it against Topic 7's dict version on 2,000 seeded lists (sizes from 0, k from 0).
ping(t) returns how many pings happened in [t - 3000, t], with times arriving in increasing order. Write RecentCounter with a deque of times: append t, pop the front while it is older than t - 3000, return the length. This is the deque port of Topic 5 Q88 (Sliding-Log Rate Limiter), kept as the warm-up. Count the total pops and assert it never exceeds the number of pings (amortised O(1) per ping). Then add one new piece of evidence: 3,000 pings at t = 1..3000 followed by one ping at t = 10000; print the pops done by that single ping beside total pops / pings, and state in a comment that the worst case is O(w) for one ping while the amortised cost is O(1). Fuzz against a scan of all earlier pings on 500 seeded sequences of up to 60 pings, with gaps from 1 to 1,500 ticks, starting at the empty sequence.
At thousands of hits per second, a deque of timestamps stores every hit. Build two counters over whole seconds that answer count(t) = hits in (t - 300, t]: DequeCounter (one deque entry per hit) and RingCounter (300 slots, one per second, each holding a count and the second it belongs to). RingCounter.hit(t) goes to slot t % 300, resetting the slot first if it holds an older second; count(t) sums the slots whose second lies in the last 300. Times never go backwards.
Fuzz both against a brute count on 300 seeded runs with gaps of up to 700 seconds (so stale slots are met), and compare the stored entries at 10 and 1,000 hits per second over 600 seconds. Say what each costs per hit and per count.
Generate the binary forms of 1..n with a queue: start with "1"; each dequeued string s is output, then s + "0" and s + "1" are enqueued. FIFO order produces them in increasing order. Write binary_numbers(n) (empty list for n = 0) and check it against bin(i)[2:] for every n from 0 to 60 and for n = 10,000. Count the queue operations and the characters produced, and print the largest queue length. This is a level-by-level walk of an implicit binary tree (trees are DSA Topic 13, named only).
A deck is revealed by this process: show the top card and remove it, then move the next card to the bottom, and repeat until none remain. Find an ordering of the deck that reveals the cards in increasing order. Simulate the process on the positions 0..n-1 with a deque to learn which position is revealed k-th, then put the k-th smallest card there. Write reveal_order(deck) (the process itself) and arrange(deck) (the answer), for any deck of distinct numbers including the empty one. Check by replaying the reveal on the result for n = 0..12 and on 500 seeded decks of up to 40 cards. Time: O(n log n) for the sort, O(n) for the simulation.
The earlier Josephus simulation used rotate and popleft and cost O(nk). The survivor's 0-based index satisfies J(1) = 0 and J(n) = (J(n - 1) + k) % n: after the first removal the circle is a circle of n - 1 people renumbered from the person after the victim. This is a recurrence in the style of DSA Topic 8, computed with a loop. Write josephus_sim(n, k) (deque) and josephus_loop(n, k); both raise ValueError for n < 1 or k < 1. Check them against each other for every n, k <= 30. Then time both at n = 10^5 for k = 2 and k = 100, and the loop alone at n = 10^6, and print the counted work beside the ratios (the clock may not show how the gap grows with k; the counts do).
Processes now arrive at different ticks. A process is (name, arrival, burst) with a one-letter name, and the list is sorted by arrival tick, so an index into it is enough: no priority queue is needed (that is DSA Topic 15, named only). Write round_robin(procs, quantum) with a deque as the ready queue. It returns (timeline, first, done): a string with one letter per tick and '.' for an idle tick, the tick each process first ran, and the tick each process finished (completion = the tick after its last run tick). quantum < 1 raises ValueError, and no processes gives an empty timeline.
The tie rule, as a comment in the code: at the end of a slice, processes that arrive by that tick join the ready queue before the process whose slice just ended goes to the back. When the queue is empty the CPU idles until the next arrival.
Definitions, written in the answer: turnaround = completion - arrival; waiting = turnaround - burst; response = first run - arrival.
-
Write the function and write
metrics(procs, first, done)that returns{name: (completion, turnaround, waiting, response)}. -
Run
[("A", 0, 5), ("B", 1, 3), ("C", 3, 2), ("D", 12, 2)]with quantum 2. Print the timeline, one table row per process and the three averages (turnaround, waiting, response) to two decimals. -
Show the tie rule matters: with
[("A", 0, 4), ("B", 2, 2)]and quantum 2, B arrives at exactly the tick A's first slice ends. Print the timeline and assert B runs before A's second slice. -
Fuzz against
round_robin_truth, a tick-by-tick oracle with a different structure (one tick per loop pass, no jumping), on 300 seeded workloads starting at zero processes.
One seeded workload (random.Random(11)) of 12 processes (name, arrival, burst): arrivals step forward by 0 to 3 ticks, bursts are 1 to 20 ticks. Run round robin (a deque ready queue; arrivals join the queue before a preempted process, the tie rule used throughout this topic) with quanta 1, 2, 4, 8, 16 and one larger than every burst. Print a table with average waiting (turnaround - burst), average response (first run - arrival) and context switches. A context switch is counted each time the CPU moves to a different process than the previous slice ran.
The hypotheses to test, computed and printed as held or not held: switches fall as the quantum grows, average response rises, and the largest quantum gives exactly the first-come-first-served timeline. Compare timelines for that last one. Then state the trade the table shows, only if the numbers support it.
A senate is a string of 'R' and 'D', one letter per senator, in seat order. Round after round, each senator who is still allowed to act, in seat order, bans the next senator of the other party in the circle (that senator loses all rights, now and in later rounds). When a senator finds no one of the other party left, their party wins. The rule is given; that banning the next opponent is the best play is a greedy argument (DSA Topic 20), named only.
Write predict_winner(senate) returning (winner, bans) with two deques of seat indices, one per party: the smaller front acts, bans the other front, and rejoins its own queue with index + n for the next round. bans counts the bans; an empty senate returns ("", 0). Show a trace for "RDDRD", then compare against senate_truth, a direct simulation over a list with banned flags, on 500 seeded strings of length 0 to 12, and assert bans <= max(n - 1, 0) each time.
People stand in a line; person i wants tickets[i] tickets (at least 1) and buys one per turn, then goes to the back of the line if they still want more. Write time_to_buy(tickets, j): the number of turns until person j has bought all their tickets, simulated with a deque of (index, remaining). A bad j raises IndexError and a ticket count below 1 raises ValueError. Then write time_to_buy_count(tickets, j) in O(n): by the time j finishes, everyone at or before j has bought min(t[i], t[j]) tickets and everyone after j has bought min(t[i], t[j] - 1). Fuzz the two against each other (starting at one person).
Hypothesis to measure: the simulation's time grows with sum(tickets) while the count's does not. Scale a seeded 40-person line by 1, 10 and 100, print the turns simulated and the time of each method, and word the verdict from the growth factors, not from fixed numbers.
Each worker owns a deque of tasks. The owner pushes and pops at the back (newest first); an idle worker steals from the front of the longest other deque (oldest first, ties to the lowest worker number), so owner and thief never touch the same end. Simulate ticks with no threads: a plain loop. Within a tick: (1) idle workers, in worker order, take a task (own back, else steal), (2) every busy worker works one tick, (3) finished tasks are recorded.
Write simulate(tasks, workers, steal) returning (finish_tick, steals, busy, done, steal_log), with every task starting on worker 0. Use 60 seeded tasks of 1 to 9 ticks and 4 workers. Print the total work, ceil(total / workers), the finish tick with and without stealing, the steals, busy ticks per worker and the first four steals. Hypothesis to check from the output: stealing brings the finish tick close to total / 4. Assert the list-scheduling bound finish <= total / workers + max(tasks), and that every task ran exactly once.
Dropping is one answer to a full queue; the other is to make the producer wait. Simulate integer ticks. Each tick the producer wants wants(t) more items, and what it could not hand over earlier is still owed (a backlog), so nothing is dropped. Within a tick: (1) the producer adds items one at a time while it is owed some and the queue is not full, (2) the consumer removes up to c items from the front, (3) metrics are sampled. If the producer is still owed items after step 1, it was blocked for that tick (a blocked tick is counted). An item's wait is its dequeue tick minus its enqueue tick.
Write simulate(capacity, wants, c, ticks) with a deque returning a dict with consumed, accepted, blocked, mean_wait, left (items still queued at the end) and owed (items the producer still holds at the end).
-
Steady producer,
wants = lambda t: 3,c = 2, 2,000 ticks, capacities 2, 4, 16 and 64. Print throughput (consumed / ticks), blocked ticks, mean wait and the final backlog per capacity. (A capacity belowcwould cap throughput at the capacity, because the consumer can never find more than that many items, so every capacity here is at leastc.) Hypotheses to check, printed as held or not held with the capacities where they fail: throughput equalscfor every capacity, and the mean wait grows with capacity. -
a bursty producer (seeded coin: 0 or 4 items a tick, average about 2) against
c = 3, capacities 4, 8, 16 and 64 (each at leastcand at least one burst of 4). Hypothesis: a larger capacity never blocks more. -
Assert that
consumed + leftequalsacceptedand thataccepted + owedequals everything the producer wanted, then state the lesson only from the printed rows.
A grid is a list of equal-length strings: '.' open, '#' wall, 'E' exit. Find every open cell's distance to its nearest exit, moving up, down, left or right. One BFS per exit and a minimum costs O(E * R * C). Putting every exit in the frontier at distance 0 gives all distances in one O(R * C) pass, because the frontier still hands out cells in order of distance. (BFS on a grid is a preview; the full treatment is DSA Topic 17.)
Write bfs_from(grid, sources) returning (dist, dequeued) with a deque frontier, a cell marked visited when it is enqueued, and bounds checked before indexing. Write per_exit(grid) and multi_source(grid); both return (dist, dequeued_total). Fuzz them against each other on 300 seeded grids (rows 0 to 8, so the empty grid is included), and print a distance grid for one example (width 3 per cell, # for walls, . for unreachable cells) with the cells dequeued by each method.
BFS gives distances; to print the route, record each cell's parent when it is enqueued, then walk back from E to S and reverse. Write shortest_path(grid, dirs=DIRS) for a grid of strings ('.' open, '#' wall, 'S' start, 'E' end) returning the list of cells from S to E, or None when E cannot be reached; a grid without an S or an E raises ValueError. Write draw(grid, path) that marks the interior cells with '*'.
Print the route for a small maze, then check that its length equals the BFS distance (computed by a separate distance-dict BFS), every step goes to a neighbour and no cell repeats. Show an unreachable E returning None. The neighbour order is fixed, so the route is always the same one, though other shortest routes may exist: on an open 4 x 4 grid, print the route for up/down/left/right and for the reversed order, and assert they differ and have equal length.
A bounded queue drained at a fixed rate turns bursty input into smooth output. Write LeakyBucket(capacity, rate) over a deque that stores each request's arrival tick: tick(now, arrivals) first adds the arriving requests (a request that finds the bucket full is dropped), then lets up to rate requests leave from the front, and returns (accepted, left, dropped, waits), where waits lists leave tick minus arrival tick for each request that left. Within a tick, arrivals come before the leak. Seeded bursty arrivals (random.Random(11): with probability 0.3 a burst of 1 to 10 requests, otherwise none), rate 2, capacity 6.
Print tick, in, out, dropped and the level for 30 ticks as columns, and assert that output never exceeds the rate on any tick. A comment should say that the bounded-queue drop sweep was already done earlier and that the leaky bucket is that queue with the consumer fixed at rate r. Then run 3,000 ticks with capacities 2, 8, 32 and 64 and print the largest per-tick input, the largest per-tick output, and the mean and maximum wait. Hypothesis to check from the numbers: the output stays at or below the rate while the wait grows with capacity, so a bigger bucket trades drops for delay. The token bucket, which lets a short burst through at full speed, is named only.
Eight window questions over one list, each with a window of k = 3: the sum, the count of positive values, the first negative value, the number of requests in the last 3 ticks, the maximum, the minimum, the gcd and the bitwise OR. Route each to the tool that fits its aggregate, and let the code print the deciding property instead of asserting it in prose:
- a running total when the aggregate can be undone (adding then removing gives back the original:
opis injective in its first argument, tested on small numbers), - a plain queue when only the items themselves are needed (first negative, recent requests),
- a monotonic deque when
opalways returns one of its inputs (max and min), - two stacks with aggregates for an associative operation with no inverse and no order (gcd, OR). The two-stack aggregator for any associative operation is built later in this topic; here, print the route and check these two rows only against
functools.reduceover each slice.
Write one solver per other tool, solve the first six questions on [12, -4, 18, 6, -9, 30, 8, -2, 15] and check every answer against a brute force over slices. Run gcd and bitwise OR on the non-negative list [12, 4, 18, 6, 9, 30, 8, 2, 15] (Python's OR on negative ints uses infinite two's complement, not taught here). Probe each question's properties on the values it actually uses, and print a routing table. k < 1 raises ValueError.
Find the length of the shortest non-empty subarray whose sum is at least k (k >= 1), or -1 if there is none. The array may hold negative numbers. This is the fix that DSA Topics 5 and 6 named for here.
DSA Topic 5 (The Negative Number Trap) showed that the grow-and-shrink window fails once negatives appear and named this method for here.
-
With prefix sums
P(DSA Topic 6), the answer is the smallestj - iwithP[j] - P[i] >= k. Keep acollections.dequeof indices whose prefix sums increase front to back. For eachj,while P[j] - P[front] >= krecordj - frontand pop the front; thenwhile P[back] >= P[j]pop the back; then appendj. Write both pops' reasons as comments. -
Fuzz against the
O(n^2)scan on 2,000 seeded arrays that contain negatives, zeros and the empty list.
Given a (negatives allowed) and k >= 1, find the largest sum of a non-empty subarray whose length is at most k, or None for an empty list.
- Show Kadane's scan (DSA Topic 2) answering the unlimited version, and print one input where it exceeds the true answer under the limit.
- With prefix sums
P, the best subarray ending atjhas sumP[j] - min(P[i])overiin[j - k, j - 1]. That minimum over a sliding window is a monotonic deque of indices (prefix sums increasing front to back). - Fuzz against the
O(n k)scan on 2,000 seeded arrays, starting at size 0.
Points (x, y) are sorted by x (equal x allowed). Maximise y_i + y_j + x_j - x_i over pairs i < j with x_j - x_i <= k. Return None when no pair qualifies.
Rewrite it as (y_i - x_i) + (y_j + x_j): for each j, the best y_i - x_i among earlier points in reach. Keep a collections.deque of indices whose y - x decreases front to back. Expire front points whose x is too far back with a while loop: several can leave at once. Fuzz against the O(n^2) pair scan, including equal x values and the empty list.
DSA Topic 5 found the longest subarray with max - min <= limit using two list-plus-head deques. Here, count all such subarrays (limit >= 0).
For each right end, every left from the window's left edge to right works, so add right - left + 1 (the counting windows of DSA Topic 5). Use two collections.deque objects: one decreasing for the max, one increasing for the min. Fuzz against the O(n^2) count on 2,000 seeded inputs with ties, limit = 0 and the empty list.
Find the maximum of every k x k block of an R x C grid of numbers (k >= 1; an empty result when k exceeds either side). The block's max is the max over its rows of each row's window max, so run the 1-D monotonic deque along every row, then along every column of that result: O(R * C) for any k.
Count the work for R = C = 200 and k = 3, 9, 27 against the naive version (compare every cell of each block). The naive count is (R - k + 1)(C - k + 1)(k^2 - 1) comparisons; check that formula against a real counted run on a small grid, then count the deque version's steps (every comparison, push and pop) on the big grid. Fuzz against the naive version on small grids, including k = 1, k equal to a side and the empty grid.
Besides the monotonic deque and the two max-stacks, there is a linear method for window maxima with no deque and no stacks. Cut the array into blocks of k. Compute each block's running max from the left (left_max) and from the right (right_max). Every window starts in one block and ends in the next (or the same), so its max is max(right_max[i], left_max[i + k - 1]).
Fuzz it against the monotonic deque version on seeded arrays (size 0, k = 1, k = n, k > n included). Time both at n = 200,000 and print the numbers and the ratio. Say what separates them if the clock does not: how much memory each needs and whether each can read a stream.
A monotonic deque works for max and min because a larger later value makes earlier ones useless. The gcd of a window has no such order and no inverse to subtract. The max-stack window earlier in this topic noted that two aggregate stacks (stacks are DSA Topic 10) work for any associative operation, and the earlier window-tool routing exercise sent gcd and OR to two stacks but only checked them with functools.reduce. Here that structure is built as a reusable AggQueue, the order rule is tested with a non-commutative operation, and the window becomes variable.
-
Short recap: DSA Topic 6 (Subtraction Needs An Inverse) showed that gcd, like max, has no inverse. A running gcd that tries to "forget" the item leaving the window can only stay or shrink. Slide a window of 2 over
[6, 4, 9, 3]and print the running-gcd answers beside the true ones. -
Build
AggQueue(op, identity)withenqueue,dequeue,queryand__len__, from two listsinboxandoutbox. Each entry carries the aggregate of itself and everything below it, as in DSA Topic 10's min-stack.inboxentries are(value, op(agg of the entry below, value)).outboxentries are(value, op(value, agg of the entry below)), so its top is the oldest item.query()isop(outbox top agg, inbox top agg), in that order. Countopcalls. -
Use it for the shortest subarray whose gcd is 1 as a variable window (enqueue on the right, dequeue from the left while the window's gcd is 1). Assert the
opcalls stay within5nand compare with theO(n^2)oracle's call count. -
Fuzz
AggQueuewithgcd,max,+and string concatenation (not commutative) against a list model. AddSwappedAggQueue, which builds the outbox aggregates in the wrong order, and show that only the concatenation fuzz catches it.
DSA Topic 6's streaming counter already expired old prefixes from its dict, but it kept every prefix in a list to know which one expires (O(n) space), and named a bounded buffer for here. That buffer is a deque of the last L prefixes. Count the subarrays with sum exactly k and length at most L, reading the numbers as a stream.
Only the prefix sums from the last L positions may pair with the current one. Keep their counts in a Counter and their values in a collections.deque; when a prefix falls out of range, decrement its count (and delete the entry at zero, so memory stays O(L)). Negatives and zeros are allowed. Fuzz against the O(n L) scan, including L = 0 and the empty stream, and check the peak memory counts on a long stream.
You may flip k consecutive bits (a window) as often as you like. Find the fewest flips that make every bit 1, or -1 if it cannot be done.
Scanning left to right, if bit i is still 0, the only window left to try is the one starting at i: any window starting earlier was already decided, and one starting later does not reach i. That is a forced move, not a choice, so no exchange argument is needed (greedy proofs are DSA Topic 20). Flipping each window directly is O(n k).
Instead, keep a collections.deque of the start positions of flips that still cover the current bit. The bit's current value is bits[i] XOR len(deque) % 2, and flips expire from the front. Fuzz against the direct version and against an exhaustive search over every set of flip starts for n <= 10 (including k > n and the empty list).
Build FrontMiddleBack with push_front, push_middle, push_back, pop_front, pop_middle, pop_back and __len__, every operation O(1) amortised.
Middle is defined like this. For a queue of m items, push_middle(x) inserts so that x lands at index m // 2, and pop_middle() removes the item at index (m - 1) // 2 (the frontmost of two middle items). Popping from an empty queue raises IndexError.
-
Use two
collections.dequeobjects,leftandright, so the queue isleftfollowed byright. State the invariant in a comment:len(left) <= len(right) <= len(left) + 1. After every operation, rebalance by moving one item between the inner ends. -
Trace these 10 operations, printing both halves after each: push_back 1, push_back 2, push_front 3, push_middle 4, push_middle 5, pop_middle, pop_front, push_back 6, pop_back, pop_middle.
-
The list model uses the same definition (
insert(m // 2, x),pop((m - 1) // 2)). Fuzz on 2,000 seeded operation sequences, starting at the empty queue, comparing every return value and exception type.
The queue from two stacks, built earlier in this topic, used two lists as stacks (append and pop, DSA Topic 10). A double-ended queue can be built the same way: front is a stack whose top is the front item, back is a stack whose top is the back item, so push_front and push_back are one append each. The trouble is a pop at an end whose stack is empty.
- Naive: when the needed stack is empty, move everything from the other stack across. Build
TwoStackDeque(balanced=False)withpush_front,push_back,pop_front,pop_backand__len__, and amovescounter (one per item copied). Loadnitems withpush_back, then alternatepop_frontandpop_back. Print the moves forn = 500, 1,000, 2,000. - Balanced: when the needed stack is empty, move only the half nearest the empty end, so each stack keeps about half. Same counts on the same sequences.
- Why it is cheap: use the potential
Phi = abs(len(front) - len(back)). An ordinary operation costs 1 and changesPhiby at most 1. A rebalance ofmitems costsmmore and dropsPhifrommto at most 1. Check on every operation of seeded random and adversarial sequences thatcost + change in Phi <= 2, so the total moves never exceed the number of operations. - Fuzz both versions against
collections.dequeon 1,000 seeded sequences starting at length 0, comparing every returned value and every exception type (IndexErroron an empty pop).
A bank has 3 tellers. Customers arrive at integer ticks (at most one per tick, seeded) and each needs an integer number of service ticks (2 to 10). Compare two layouts on the same arrivals:
- Layout A: one shared FIFO line; any free teller takes the front customer.
- Layout B: one line per teller; each arriving customer joins the line with the fewest people waiting plus the one being served (lowest teller number on a tie) and stays there.
-
Step 1: write
simulate(arrivals, shared)tick by tick with deques. The order inside a tick is fixed and stated in a comment: arrivals join, free tellers start the next customer, then the tick is sampled. -
Step 2: for each layout return the mean wait, the maximum wait (wait = service start tick - arrival tick) and blocked ticks: ticks in which a teller was idle while a customer was waiting in some line.
-
Step 3: run both at three loads (arrival probability 0.30, 0.40, 0.46 per tick, so about 60%, 80% and 92% of the tellers' capacity) for 5,000 ticks of arrivals, then serve everyone left over. Print one table.
-
Step 4: state which layout won on the mean and on the maximum at each load, using booleans computed from the table. Hypothesis to test: the shared line has the lower mean wait and a much lower maximum wait, because in layout B a customer can sit behind a long service while another teller idles. Report where the table disagrees.
For a stable queue, Little's law says the average number of customers in the system is L = lambda * W, where lambda is the arrival rate and W the average time a customer spends in the system. Check it by simulation.
One server, 10^5 ticks, a customer arrives with probability p per tick, service takes 1 to 3 ticks (mean 2), so utilisation is 2p. Run p = 0.25, 0.40, 0.45, 0.475 (utilisation 0.5, 0.8, 0.9, 0.95). Measure L (the number of customers present, sampled once per tick after arrivals and before service), lambda (arrivals per tick) and W (mean ticks from arrival to the last service tick, inclusive) separately, then print L, lambda * W and their relative difference.
Hypotheses to test: L and lambda * W agree within a few percent, and W rises sharply as utilisation approaches 1. Then run one case until the system drains and show that the identity becomes exact. Queueing theory beyond this (why W explodes) is named only.
Plain round robin by packets is unfair when packet sizes differ: every flow sends one packet per round, so a flow of 1,500-byte packets gets 15 times the bytes of a flow of 100-byte packets.
- Three always-backlogged flows, a deque of packet sizes each: A sends 1,500-byte packets, B sends 100-byte packets, C sends seeded sizes from
(100, 500, 1500). Run 200 rounds of plain round robin and print the bytes each flow sent. - Deficit round robin: each flow has a quantum (bytes per round) and a deficit counter. A deque of active flows is the ready queue. On its turn a flow adds its quantum to its deficit and sends packets from the front while the head packet fits within the deficit, subtracting each size; if packets remain it goes to the back of the active deque, and if it emptied its deficit resets to 0. A round is one pass over the flows that were active when it began. Quanta A 1,500, B 1,500, C 3,000. Run 200 rounds and print the bytes,
bytes / quantum, and the deficit left over. - Hypothesis: bytes served become proportional to the quanta. Check the exact conservation
bytes + leftover deficit == rounds * quantumfor each flow, and say whybytes / quantumis within 1 of the round count (the leftover deficit is smaller than the head packet, and every quantum is at least the largest packet). - Weighted round robin for equal-size packets: a flow gets
weightturns per round. With weights 1, 2, 3 and 1,000-byte packets, print the bytes.
Find the fewest steps from S to E on a grid of strings ('#' is a wall; moves are up, down, left, right) when you may break at most one wall, meaning one step may enter a '#' cell.
The state is no longer a cell: after breaking a wall the search is in a different situation. Search over (row, col, used) states, which is two copies of the grid, "before the break" and "after the break". Stepping into a wall is allowed only from used = 0 and leads to used = 1. The frontier is a deque, each state is marked visited when enqueued. Return (steps, states_seen), with -1 when E cannot be reached, and handle an empty grid.
Print a grid that is blocked by a full wall, with and without the break. Check against a brute force that removes each wall in turn and runs a plain BFS (O(W * R * C) for W walls) on 1,500 seeded grids, and assert that states_seen never exceeds 2 * R * C. General state-space search is DSA Topic 17, named only.
Events (time, value) arrive with non-decreasing times (several events may share a time). After each event, report the maximum value among events in the half-open window (t - T, t].
The window now holds a varying number of events, and one new event can push out several old ones after a long gap. So the front of the monotonic deque (it holds (time, value) pairs, values strictly decreasing from front to back) expires with a while on time, not the if that a count window uses. Write window_max_by_time(events, T). Trace [(0, 5), (1, 4), (2, 3), (50, 1)] with T = 10, printing the deque after each event, so that three entries visibly leave on the gap. Fuzz against a scan of every earlier event, starting at zero events, with bursts of equal timestamps and gaps long enough to empty the window.
Merge several iterables by taking one item from each in turn until all are exhausted. Write merge_deque(iterables): a deque of iterators; pop the front, call next(), and put it back unless it raised StopIteration. It returns the merged list and the number of next calls.
Compare with merge_cycle(iterables), which loops over a list of iterators again and again and keeps an exhausted flag per iterator: dead iterators are visited on every pass. Count visits when one iterable is much longer than the rest (50 lists of length 5 and one of length 2,000). Check both against an oracle built from itertools.zip_longest with a private sentinel, on lists and on generators, including no iterables at all.
Three workloads, three containers: a list, a collections.deque, and a hand-written growable ring with O(1) indexing (RingDeque: push_back, pop_front, __getitem__, __len__).
-
Step 1: write
RingDequewith the head-index and% len(slots)arithmetic from the ring questions (doubling when full), andbest_of(fn, repeats=3, setup=None)taking the minimum of 3 runs, building each run's container insetupoutside the timed region. -
Step 2: time three workloads. Front-heavy: a queue of length 10^4, then 20,000 steps of enqueue + dequeue. Index-heavy: a sequence of 10^5 items, then 3 passes of 10,000 reads at seeded random indices. Mixed: a queue of length 200,000, then 2,000 steps of enqueue, dequeue and one read of the middle item.
-
Step 3: print a table of milliseconds and each container's ratio to the fastest in its workload. Make a verdict about a workload only where the best container beats the runner-up by at least 2x, and say "no verdict" otherwise. Test the hypotheses: the deque wins front-heavy, the list wins index-heavy, and the ring never wins the clock but is never the worst by a wide margin. Every sentence must follow from the printed table.
The two-stack queue does O(1) amortised work, yet one dequeue can move every item. Over the same 100,000 seeded operations (52% enqueues, never a dequeue on an empty queue) record, per operation:
- the items moved by a
TwoStackQueue(a transfer moves each item once), - the items copied by a growable
RingQueuethat doubles when full (the resize is the spike), - and for
collections.dequethe time of each operation sampled withtime.perf_counter(it has no moves to count; a deque allocates a fixed-size block now and then, never copies its items).
Print each structure's total, maximum and a histogram (buckets 0, 1, 2-9, 10-99, 100+) for the two counted ones. Hypothesis: the totals are close, while the maxima are orders of magnitude above the mean. Also show the adversarial sequence (n enqueues, then one dequeue). When it matters: a system that must answer every request within a bound. Worst-case O(1) queues from stacks exist (Hood-Melville, Okasaki) and are only named here.
Five problems look like queues and are not. For each, run the wrong tool and the right tool and print the counted cost (or the wrong answer) side by side.
- Serve the most urgent first (lower number = more urgent). A FIFO queue serves in arrival order, which is wrong. A list kept sorted with
bisect.insortis right but costs O(n) per insert; count the items shifted for 2,000 seeded urgencies, beside the roughlylog2(n)swaps per insert of a priority queue (DSA Topic 15, named; it is a bound here, not a measurement). - Undo the last action. A queue's
dequeuereturns the oldest action; a stack (DSA Topic 10) returns the newest. - Cancel an order in the middle. Finding and deleting it in a
dequescans; instead mark it in aset(DSA Topic 7) and skip it lazily at dequeue. Count comparisons and skips for 1,000 cancellations among 2,000 orders, and assert both serve the same orders. - All items known before the first dequeue. A
pop(0)drain movesn(n - 1)/2items; reverse once andpop()copiesn. This one is a citation row: print the two formulas for onen, measured in DSA Topic 1, and run nothing new. - The maximum of a window. Keeping all window items in a queue and scanning costs
k - 1comparisons per step; a monotonic deque costs at most2nin total.
A growable ring keeps slots, head (the slot of the front item) and size. Resizing it is where rings go wrong, because once the ring has wrapped, the queue's order is not the order of the slots. Write the correct RingQueue (doubling, starting from capacity 2) and two plausible broken subclasses that override only the resize:
ExtendRinggrows the list in place,slots + [None] * capacity, and keepshead;StaleHeadRingcopies the items in queue order to slots0, 1, 2, ...but forgets to resethead.
-
Write
shortest_failure(cls): try every operation string ofE(enqueue the next number 0, 1, 2, ...) andD(dequeue, or recordIndexError) withitertools.product, length 0 up to 8, shortest first, and compare each output with a list model. For each broken ring print its shortest failing string as a trace: one line per operation with the raw slots,head,size, the output and the truth, marking the first wrong line. -
Show the fixed ring has no failing string up to length 8, then fuzz it on 2,000 seeded sequences starting with the empty one.
State each operation's time and space, amortised and worst case.
A dedupe filter rejects an item if it equals one of the last k accepted items. TrustingFilter keeps a set for fast lookups and a deque(maxlen=k) for the order, and trusts maxlen to do the eviction. Q14's moving average met this trap with a running total, and Q35 built the explicit set + deque eviction; here the stale set causes permanent wrong rejections, not a drifting number.
- Run it with
k = 3on a seeded stream of 40 values from 0 to 5, besidededupe_truth, anO(n * k)scan of the accepted list. Print the stream, the first index where the two disagree with the filter's state just before it, and the number of wrong decisions. - Write
DedupeFilter, which evicts explicitly: when the order is full it pops the front itself and removes that item from the set. Check it on the same stream and fuzz it on 1,000 seeded streams starting at length 0. - A second silent drop: a recent-events buffer
deque(maxlen=4)takes new events withappend, and puts a failed event back at the front withappendleftso it is retried first. Show what a full buffer loses.
A job runner walks its queue with for job in q: and appends each job's follow-up jobs to q as it goes (job "a" spawns "a1" and "a2"; two-letter jobs spawn nothing).
- Run it on a
dequeand print what happens (the exception's type name and message). - Run the same loop on a list. Print what runs, and say why it is still a trap.
- Inside
for job in q:on a deque, doq.append("x"); q.popleft(), which leaves the length unchanged. Print what happens. (Removing from a list while looping over it, and the dictRuntimeError, were DSA Topics 2 and 7.) - Fix it two ways:
while q: job = q.popleft(), and a snapshotfor job in list(q)when new jobs should wait for the next pass. State the cost of each.
Show four ways a deque surprises someone used to lists, each printed from a run:
d[1:3]: what happens, and what to use instead (itertools.islice, orlist(d)once).deque([1, 2]) == [1, 2].deque([0]).extendleft([1, 2, 3]), and how to keep the order.indexed_sum(d), a loop readingd[i]for everyi, againstiterated_sum(d), which loops overddirectly, atn = 10,000, 20,000, 40,000, 80,000.
Hypothesis to measure: the indexed loop's time roughly quadruples per doubling of n, while the direct loop roughly doubles. Print a table with min-of-3 times per pass, the growth factor per doubling, and block_steps(n): a computed count of the block hops that CPython's deque layout (64-item blocks, each read walking from the nearer end) costs for the indexed loop. Let the count carry the per-doubling claim, and give a clock verdict only on the whole 8x span, against a cut-off far from both linear (8x) and quadratic (64x) growth.
The two-stack queue keeps inbox and outbox (lists used as stacks) and transfers only when outbox is empty. Write it as TwoStackQueue with a moves counter, plus two broken versions:
EagerTransferpoursinboxontooutboxon every dequeue, even whenoutboxstill holds items;PourBackpours everything ontooutbox, pops the oldest, then pours everything back toinbox.
- With
itertools.product, search every string ofE(enqueue 0, 1, 2, ... in turn) andDup to length 8, shortest first, for a string where a version's dequeue outputs differ from a list model. PrintEagerTransfer's shortest one, got beside truth, and show the other two pass every string. PourBackis correct, so count what it costs: on one seeded string of 10^4 operations (three enqueues to each dequeue), print the moves ofTwoStackQueueandPourBack, and checkTwoStackQueuemoves at most one per enqueue.- Fuzz all three on 1,000 seeded strings starting with the empty one, and print the failure counts.
Three plausible bugs in window-maximum code, each one run until it gives a wrong answer:
one_pop_bug(items, k)keeps indices, but its back pop isif items[dq[-1]] <= x: dq.pop()instead ofwhile, so a large new value clears only one smaller candidate.read_first_bug(items, k)keeps indices correctly but appends the front's value to the answer before expiring the front.time_if_bug(events, w): events are(t, v)with strictly increasing integert, and the answer at timetis the maximum over the times in(t - w, t]. It expires withifinstead ofwhile.
Then:
-
Write the reference
window_max(items, k)(indices,whileat the back,ifexpiry at the front, read after expiring) with its invariant comment and O(n) argument,window_max_truthandtime_max_truthas slice scans, andsmallest_failure(fn, truth, make): a seeded fuzz from size 0 that keeps the failing input with the fewest items. Print each bug's smallest failing input with its output beside the truth. -
Fix each one: the reference restores the
whileat the back and reads after expiring;time_maxexpires withwhile. Fuzz the fixes on 2,000 seeded inputs from size 0, and explain why the back needswhilefor every window kind, while the front needs it only for a time window.
shortest_at_least(a, k) from Q51 finds the shortest non-empty subarray with sum at least k (k >= 1, negatives allowed) with prefix sums and a deque of increasing prefix sums. Run three plausible wrong answers through one seeded fuzz of 4,000 arrays (sizes 0 to 7, values -4 to 6) against the O(n^2) scan shortest_truth:
grow_shrink, DSA Topic 5's grow-and-shrink window (DSA Topic 5 Q71 showed it fails with negatives; here only its failure count and smallest case);no_back_pop, the prefix deque without the back pop;first_found, which returns the first qualifying length it finds instead of the shortest.
For each, print the failure count and the smallest failing input (fewest items first) with its output beside the truth; a variant that never fails is reported as correct. Then explain the two counts that come out equal.
A BFS on a grid can mark a cell visited when it is enqueued or when it is dequeued. Write bfs_mark_on_enqueue(grid, start) and bfs_mark_on_dequeue(grid, start), each returning (dist, enqueues); the late version skips a cell that comes off the frontier a second time.
-
On open grids of 10 x 10, 20 x 20, 40 x 40 and 80 x 80, starting at the top-left corner, check that the two give the same distances and print a table of cells, both enqueue counts, the excess and the late/cells ratio. Hypothesis to measure: the late version enqueues more cells than the grid has, and the excess grows with the grid. Explain the excess you measure.
-
bfs_never_mark(grid, start, cap)never marks anything. Run it on the 10 x 10 grid with a cap of 20,000 dequeues and report that the cap was hit and how big the frontier had grown.
State the time and space of each version.
Write search(grid, use_stack), a grid search that marks cells when they are added and returns (distance recorded for E, route), or (-1, None). The only difference between the two modes is one line: popleft() for a queue, pop() for a stack. Search 3,000 seeded random grids (1 to 4 rows, 2 to 4 columns, about a quarter walls, random S and E) for the smallest one where the two distances differ. Print that grid twice side by side with each route drawn as *, both distances and both routes as cell lists.
Write round_robin(procs, quantum, preempted_first=False, off_by_one=False) for processes (name, arrival, burst) sorted by arrival, returning (timeline, done, switches): one letter per tick with '.' for idle, each process's completion tick, and the number of times the CPU moved to a different process. Q41 stated one tie rule; this question is about the choice and a counting bug.
- The tie. A process that arrives during a slice is ahead of the preempted process under any rule. One that arrives exactly as the slice ends is a tie: by default it joins before the preempted process;
preempted_first=Truereverses that. Run[("A", 0, 5), ("B", 2, 3), ("C", 4, 2)]with quantum 2 under both rules and print the timelines, waiting times (turnaround - burst), averages and switches. Then count, over 1,000 seeded workloads, how often the two timelines differ. - The off-by-one. With
off_by_one=Truea process is put back whenremaining >= quantuminstead of>, so one with exactly one quantum left runs it, rejoins with 0 remaining and later gets a zero-length turn. Run[("A", 0, 3), ("B", 0, 4), ("C", 0, 4)]with quantum 2 both ways; print the timelines, completions and switches. - Fuzz both rules, fixed and buggy, against
round_robin_truth, a tick-by-tick oracle that takes the same tie rule.
A queue is a buffer, and a buffer only helps when work leaves at least as fast as it arrives. Simulate one server for 8T ticks with T = 10,000. A customer arrives with probability p per tick and needs 1 to 3 ticks of service (mean 2), so the utilisation is 2 * p. Use utilisation 0.9, 1.0 and 1.1 (the arrival probability is util / 2) and write simulate(p, ticks, seed, servers=1, bound=None, checkpoints=()), which returns the waiting-line length at each checkpoint tick, the average line length over the run, and the number of customers dropped.
For each utilisation, average five seeded runs and print the line length at T, 2T, 4T and 8T, plus the average line length measured over only the first T ticks and over all 8T. Hypotheses to test: at 0.9 the length levels off; at 1.1 it grows about in step with time; at 1.0 it keeps growing, more slowly. Then show why an average over one short run misleads, and try the three fixes at utilisation 1.1: a second server, a bound on the line with a drop policy, and (named in the output) lower arrival rate. Say what the numbers show, using only the numbers printed.
Dequeuing with pop(0) has a bad name, and it deserves it only when the queue is long. Hold a queue at a fixed length m and do 20,000 enqueue-plus-dequeue pairs, once with a list (pop(0)) and once with a deque (popleft), for m = 1, 2, 4, ..., 32768. Build each queue in the untimed setup of a min-of-3 timer, so no run sees a queue another run emptied.
Print, per m, the items pop(0) shifts per call (counted, not timed), both times and the ratio. Compute the break-even as a number: the first m in your sweep from which the list needs at least twice the deque's time at every larger m too (one noisy small row must not decide it). Give a clock verdict only on rows at least 8x away from it (m <= break-even // 8 or m >= break-even * 8, and only among the extreme sizes m <= 16 and m >= 16384, so that run-to-run noise in the break-even does not move a label) and print "no clock verdict" on the rest. Hypothesis to test: the break-even is around ten items. The answer prints whether it held or was rejected and the break-even it measured (expect a figure far above ten, in the hundreds or thousands, though the exact value varies by machine). Say what pop(0) costs in terms of the queue's length against the number of operations.
Three window queues each have one off-by-one bug. Write time_max_buggy, avg_buggy and neg_buggy and their fixed versions, with a brute-force *_truth beside each:
- Maximum over the last
Ttime units (a monotonic deque of(t, v)events, times non-decreasing) that expires the front withdq[0][0] < t - T. The window is meant to be the half-open(t - T, t]of the time window in Q66, but this keeps an event exactlyTold, which gives[t - T, t]. (Each event reports the maximum of the window ending at its own time.) - Moving average of the last
kitems that divides bykbefore the window is full. (A partial window averages what it holds.) - First negative number in every window of size
kthat starts reporting ati = 0instead ofi = k - 1. (Report 0 when the window holds no negative number.)
Find each bug with a seeded fuzz that starts at size 0, then shrink the failing input (drop one item, or make k smaller, while it still fails) and print the smallest case with the truth and the buggy answer side by side. Show that each fixed version matches the truth on thousands of seeded cases.
Four ways of sharing a queue by accident. Reproduce each, print the damage, and fix it:
backup = q, then drainingqemptiesbackuptoo.def collect(job, q=deque()): the default queue is built once, whendefruns. Print one line showing that two calls return the same object.copy.copy(q)(anddeque(q)) copies the deque but not the job dicts inside it. Print one line showing the order is independent and one line showing the items are shared.- A bounded queue
q = deque(maxlen=2): copy it withdeque(q)and withq.copy(), print bothmaxlenvalues, append one more job to each copy, and print which copy grew and which evicted its oldest job.
Items 1 and 3 repeat alias and shallow copies from Python Topic 15 and DSA Topic 10's undo-snapshot question, and item 2 repeats the mutable default from DSA Topics 2 and 8 (Python Topic 15 has the class-level version). Here they are the queue's forms, so keep them short. Item 4 is the main exercise, because only queues have it: deque(q) copies the order but silently drops maxlen. copy.deepcopy for independent items is named, not rebuilt.
Three queue benchmarks print confident numbers and mislead. Reproduce each, print its wrong conclusion, and fix it. Write best_of(fn, repeats=3, setup=None) so that, when setup is given, each run times fn(setup()) only.
- Time a
popleftdrain with a timer that runs it three times on one queue built once outside. Print the three run times. - Compare 20
pop(0)calls on a list of 100,000 against 20popleftcalls on a deque of 100,000, with the construction inside the timed function. Print the ratio, then the ratio with construction insetup. - Drain by
pop(0)againstpopleftat n = 100 only, and conclude that lists make fine queues. Then repeat at n = 100, 1,000, 5,000 and 20,000, printing the number of moves,n * (n - 1) / 2, beside each time.
The same trap as an in-place sort benchmark was met in Topic 9; this is its queue form. State the fix for each and choose sizes from the cost model.
Build ArrayDeque, a complete growable ring deque, and check it against collections.deque.
- All four end operations:
append,appendleft,pop,popleft; capacity doubles when full and halves when a quarter full (a minimum capacity of 4). - O(1) indexing, negative indices too, with
__getitem__and__setitem__;IndexErrorout of range,TypeErrorfor a non-integer index. - Iteration that raises
RuntimeErrorif the deque changes during the loop (a modification counter, ascollections.dequedoes);__eq__,__repr__,__len__. extend,extendleft,clear, androtate(n)by moving items (cost O(min(k, size - k))).- An optional
maxlen: an append on a full deque drops the front item, anappendleftdrops the back item, andmaxlen=0keeps nothing. - A
movescounter for resize copies.
Fuzz it against collections.deque on 20,000 seeded operations (sizes from zero, maxlen of None, 0, 1, 3 and 8), comparing every return value and every exception type; fuzz iteration under mutation separately. Show the amortised cost of growth as a count. Benchmark the end operations and middle reads (d[n // 2]) at n = 100,000 against deque, print the ratios, and write a short report saying which to use for which workload. A hypothesis to test: deque wins at the ends and ArrayDeque wins in the middle.
Simulate a job queue with workers and retries. Jobs arrive on a seeded schedule (Plan.arrivals[t] is the list of job ids arriving at tick t). Each tick up to workers jobs are taken from the front of a FIFO, and each gets one attempt that takes one tick. An attempt fails with a seeded probability (the outcome of attempt a of job j is Plan.fails[j][a], drawn up front so it cannot depend on scheduling). A failed job goes to a retry queue and is ready again delay ticks later; it is retried at most 3 times, then lands in a dead-letter list.
Write run(plan, workers, delay) returning completed, retried, the dead-lettered job ids, the mean and the maximum time to completion (completion tick minus arrival tick), and done_at. State the order inside a tick in a comment: arrivals join first, then the retries that are ready join, then the workers act. Because every delay is the same, the retry queue stays in ready-time order as a plain deque; assert it on every push, and show with a tiny example why unequal delays (say backoff) would not (a priority queue, DSA Topic 15, named only).
Fuzz run against run_slow, an oracle that re-examines every job on every tick, from zero jobs up. Print a table of runs for several failure rates and delays.
Write a scheduler simulator. A Proc(name, arrival, bursts) has CPU bursts alternating with I/O waits: bursts = [cpu, io, cpu, io, ..., cpu], every entry at least 1. A process that starts I/O leaves the ready queue and rejoins when its wait ends; the simulator finds it by scanning the blocked list each tick (O(blocked) per tick; a heap would do better, DSA Topic 15, named).
Write schedule(procs, quantum, switch_cost) returning the Gantt string (one character per tick: the process name, . idle, x for a context-switch tick), completion, first_run, switches and busy. State the tie rule in a comment: at the start of a tick, arrivals join first, then I/O returns in the order they blocked, then the process preempted at the end of the previous tick joins last. A context switch is counted each time the CPU moves to a different process than the last one that ran, and costs switch_cost ticks.
Report, per process or on average: turnaround (completion - arrival), waiting (turnaround - total CPU - total I/O: the ticks spent ready or being switched to), response (first run - arrival), and CPU utilisation (useful ticks over total ticks). Compare first-come-first-served (a quantum nobody reaches) with quanta 2, 4 and 8 on three seeded workloads (CPU-bound, I/O-bound, mixed), and print one Gantt chart. Fuzz schedule against schedule_slow, a tick-by-tick oracle with no queue that also counts waiting ticks directly.
Build a multilevel feedback queue: three ready queues (deques) with quanta 2, 4 and 8. A new process starts at the top level; using its whole slice moves it one level down; giving up the CPU early for I/O keeps its level. The scheduler always serves the highest non-empty level, and a running slice is never cut short. Write mlfq(procs, quanta, boost=None) (plain round robin is quanta=(4,)), where every boost ticks all unfinished processes go back to the top level. State the order inside a tick in a comment.
Compare plain round robin (quantum 4) with the feedback queue on a mix of three batch and eight interactive processes (Proc(name, arrival, bursts) as in the scheduler project: CPU and I/O bursts alternating). Hypothesis to test: interactive processes wait less per CPU burst under the feedback queue. Then show starvation: one long job and a short job every 2 ticks keep level 0 busy; print the long job's wait for boost periods of never, 400, 200, 100, 50 and 25, along with its longest stretch without running and the shorts' mean first response. Fuzz mlfq against mlfq_slow, an oracle with no queues, from zero processes up.
Build LogMonitor for a stream of events (time, endpoint, latency_ms, status) with whole-second times that never go backwards. After every observe(event) it keeps four live metrics, each with its own queue:
- the last 50 lines (
deque(maxlen=...)); - requests in the last 60 seconds, a ring of 60 buckets plus a running total (gaps in time must clear the buckets that left the window);
- the maximum latency over the last T seconds, a time-based monotonic deque of
(time, latency); - the error rate over the last 1,000 requests (status 500 or more), a queue plus a running count.
It raises an alert when a threshold is crossed (error rate over 5% once 200 requests have been seen, max latency over 900 ms, more than 450 requests in the last 60 seconds) and logs a line when each condition starts and when it clears. Check every metric and every alert state against brute, a scan of the whole history, after every event of a fuzz run (small windows, long gaps, from zero events up). Then print the alert log for a crafted incident: normal traffic, a bad deploy with errors and slow answers, recovery, and a flash crowd.
Build a Pathfinder for a text maze: '.' open, '#' wall, 'S' start (there may be several), 'E' end, and digits for teleport pads: every pad is one step from every other pad with the same digit, so a pad is just a cell with a far-away neighbour and the search is still a plain grid BFS. Pathfinder(grid, diagonal=False) moves up, down, left and right, and with diagonal=True also along the four diagonals, after the straight moves. It answers:
route(): the shortest route from anySto the firstE(orNone), drawn on the maze with'*'. Stop the search the momentEis enqueued.bfs(sources): the distance from the nearest of several starts to every cell, in one pass (Q47's multi-source idea).within(start, d): the set of cells reachable in at mostdsteps, expanding no cell at distanced.
Count the cells dequeued by each query. Print the route with 4 and with 8 directions and with the pads removed, a distance grid from both starts, and within for d = 2, 5 and 10. Then fuzz every query on 400 seeded mazes of 0 to 6 rows, in both direction modes, against frontier_truth, an oracle that grows the reached set one step at a time with plain sets: same distances, a route as long as the BFS distance that moves only between neighbours, and the same within sets. (Q48 rebuilt a single route from parents; this puts the queries together.) State the time and space of each.
An N x N packet switch has N inputs and N outputs. Each tick, each input receives a packet with probability load, addressed to a uniformly random output. Each output can accept at most one packet per tick, and each input can send at most one.
With one FIFO queue per input, only the front packet of each queue can compete. When several fronts want the same output, a round-robin pointer at that output picks the winner and the others wait, together with every packet behind them, even if those packets want outputs that are idle. That is head-of-line blocking. With virtual output queues (VOQ), each input keeps one queue per output. Each output grants one requesting input in round-robin order, and each input accepts one of its grants in round-robin order, so a blocked packet blocks nobody else.
Write simulate(n, load, ticks, voq) returning the throughput (packets delivered per port per tick) and the mean number of packets queued per input, and assert that no packet is lost. Print both designs at N = 8 for rising load, and at load 1.0 for N = 4, 8 and 16.
Hypotheses to measure, not assume: FIFO throughput saturates well below full load (a classic result puts the large-N limit at 2 - sqrt(2), about 58.6%), and VOQ removes most of the blocking. Word the conclusion from the numbers you print.
Write the engine of the game Snake. The body is a deque of cells with the head at the right end. A move appends the new head and pops the tail, unless the snake eats, in which case the tail stays and the snake grows, so a move is O(1). A set of occupied cells makes the collision test O(1). The set must be updated in the right order: the tail cell frees before the head moves in, so moving into the cell the tail is just leaving is legal. Running off the board or into the body ends the game. Food appears on a free cell chosen by a seeded random.Random.
- Write
Snake(rows, cols, seed, free_tail_first=True)withmove(ch)forchin"UDLR"andframe()returning ASCII rows. Replay a move string from a simple greedy player on a 6 x 10 board, and print the frames for the start, the first two moves and the end, side by side, plus the score. - Show what the order of the collision test changes: a snake of length 4 that chases its own tail round a 2 x 2 square, with the tail freed first and then second.
- Write
ListSnake, which keeps the body in a plain list and rescans it on every move, and use it as the oracle on 500 seeded games (random and greedy move strings). Compare body, score, food and state, and count the cells the list version scans against the deque version's single set lookup per move.
Build one engine for every window in this topic. Window(op, kind, size) takes kind = 'count' (the last size items) or 'time' (items with t > now - size, where now is the latest time pushed; times never decrease and may repeat), push(value, t) and query(), which returns None on an empty window. The engine picks its path from the op:
max,min: a monotonic deque (the Practice band's).sum,count: a running total, because these ops have an inverse.gcd,and,or,concat: no inverse, so the two-stack aggregator (Q57's, with(value, agg)entries). Its answer is op(outbox agg, inbox agg), in that order, so string concatenation comes out in window order.
An unknown op raises ValueError. Fuzz every op and both kinds on seeded event streams of 0 to 29 events against window_truth, a brute force that rebuilds each window and folds it with functools.reduce. Then push 10^5 events through a count window of 1,000 for one op on each path, and print the elementary operations per event (deque pushes and pops, additions and subtractions, stack pushes, pops and transfer moves) beside the brute force's fold length.
Three stages, parse, transform and write, each with a speed in items per tick, are joined by two bounded queues of the same capacity. Parse never runs out of input. A stage moves at most its speed per tick, and never more than the items waiting or the room left in the queue after it, so a full queue stops the stage before it and backpressure travels upstream (Q46 had one producer and one consumer; this chains three). Each item carries the tick it was parsed, so the latency of a written item is the write tick minus that tick.
Write run_pipeline(speeds, cap, ticks, jitter=None, trace=0). Print the occupancy of both queues and the items written per tick for the first 30 ticks, then a summary table (throughput, latency and mean occupancy, measured over the second half of the run) for three speed patterns, with the bottleneck at each stage, and capacities 4, 16 and 64.
Hypotheses to measure: throughput equals the slowest stage's speed; queues upstream of the bottleneck fill while those downstream stay near empty; bigger buffers raise latency, not throughput. Then let every stage's speed vary at random around an average of 3 (seeded) and test the last hypothesis again.
An interviewer says: "Tell me about queues." Give a six-part answer, and back each part with a few printed lines from code you run:
- FIFO, and what
pop(0)costs on a list. - The circular buffer, and why head == tail cannot tell full from empty on its own.
deque: O(1) at both ends, and its weak spot in the middle. Timed[0]againstd[n // 2]at two sizes and give a verdict only if the numbers are far apart.- The queue from two stacks, and its amortised proof: count the moves and the worst single dequeue.
- The monotonic deque, and why it is O(n): count appends and pops.
- The queue inside BFS: why FIFO gives shortest distances on a grid.
Five pieces of queue code each have one bug. For each, reason first: say what goes wrong and give the smallest input that shows it. Then run the code and print your prediction beside what you observe.
- A waste-one-slot ring (capacity 3) whose length is
tail - head, without the modulo. Find the shortest enqueue/dequeue sequence that breaks it with anitertools.productsearch. What doeslen()do with the result? - A grid BFS that does its bounds check with
try: ch = grid[nr][nc] / except IndexError: continue. - A stack built from two queues whose
top()forgets to put the item back. - A moving average that subtracts the arriving value instead of the leaving one.
- A round robin that puts a process back while
remaining < 0instead of> 0. (Q80's>=off-by-one was a different bug.)
Finish by fuzzing the fixed versions on 300 seeded cases against simple models: a list, a frontier-set BFS, a list stack, a slice average and a tick-by-tick schedule.
Choose a structure for each of six workloads, and back each choice with counted work:
- A print spooler.
- The last 1,000 lines of a log.
- The maximum of a sensor's readings over the last minute (1,000 readings).
- A queue that must also report its minimum.
- Tasks with priorities.
- The BFS frontier on an open 300 x 300 grid.
For each, count the work the choice does against the obvious alternative (shifts for list.pop(0) or del lines[0], reads for a min() rescan), and print them as one table. Priorities need no new count: name the structure and cite Q70, which counted the sorted-list insert cost. The sensor window is the fix DSA Topic 10 deferred and Q70 counted, so it gets no table row: add one timing on it, where the counts (max() rescan reads against deque ops) predict a large gap (the clock gap is smaller, since max() reads run in C), and give a verdict only if the measured ratio is far from 1. Where a short queue makes the alternative harmless, say so.
Run a mock interview on rotting oranges as a transcript that prints. In a grid, 0 is empty, 1 is a fresh orange and 2 is a rotten one. Each minute, every fresh orange next to a rotten one (up, down, left or right) rots. How many minutes until every orange is rotten, or -1 if some never rots? Answer with a multi-source BFS by layers (Q47 put every source in the frontier at once). Then take the follow-ups:
- Which oranges never rot, and the minute each cell rots, as a grid.
- Which rotten orange reached each orange first. Ties go to the source that comes first in row-major order. Explain why the BFS keeps that rule by itself.
- Fresh oranges infected from outside at given minutes.
- A 3-D crate, with 6 neighbours per cell.
- Thick-skinned oranges (3) that take 2 minutes to rot. Keep every step at one minute; arbitrary non-negative weights need Dijkstra (DSA Topic 18, named only).
Check each follow-up on 300 seeded grids, starting with the empty grid, against a minute-by-minute brute-force simulation.
Build a warehouse dispatch simulator on a grid map ('D' the dock, '#' racks, lowercase letters the shelves).
- Orders
(id, tick, shelf)arrive on a seeded schedule into a bounded order queue. An order that finds the queue full is rejected and counted. An order for a shelf not on the map is counted as unroutable. - Idle robots wait in a
dequeand take orders in turn. One BFS from the dock gives the distance to every shelf, and a trip takes twice that distance. - Simulate tick by tick in a stated order, with no priority queue (an event heap is DSA Topic 15).
- Keep four live metrics:
- a moving average of the last 50 order waits (a deque and a running sum);
- the maximum wait over the last 200 ticks (a monotonic deque over a time window);
- the last 20 events (
deque(maxlen=20)); - the queue length every tick.
Fuzz every metric after every tick against a brute-force recomputation from the full history, on seeded small configurations that start at zero ticks and zero orders. Then run four workloads, light, busy, overloaded and a burst of 40 orders at once, and print a summary table, the robots' capacity in orders per tick, and the events kept just after the burst. State the time and space of each part.
Stuck? Solve it with a mentor.
Your first 1-on-1 session is free.