Stacks & Monotonic Stacks: 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 stack is last in, first out (LIFO): the item that comes off is always the most recent one still there. In Python a list with its top at the end is a stack: stack.append(x) pushes, stack.pop() pops, stack[-1] peeks, and not stack tests for empty.
Trace these 8 operations, printing the stack after each one: push 1, push 2, push 3, pop, push 4, pop, pop, push 5. Then push 10, 20, 30, 40 and pop everything, and show the pops come back in reverse push order. Every pop and peek must be guarded by an emptiness check. Show what happens without the guard.
Python Topic 15 built a Stack class with push, pop, peek and is_empty. This version adds what a DSA course cares about: the cost of each method in a comment, len() and truth testing, iteration from top to bottom without copying, and an EmptyStackError that names the operation that failed.
Fuzz it against a bare list on 10,000 seeded operations (including pops and peeks on empty). Then time 10^6 pushes followed by 10^6 pops through the class and through bare append/pop, and print the ratio. What ships is the bare list; say what the class costs, from your printed numbers.
Put the top of a stack at the front of a list and push becomes insert(0, x) while pop becomes pop(0). Every other item slides one slot, so an operation costs the current depth, not O(1). n pushes then n pops at the front cost n(n-1) shifts. DSA Topic 1 timed this and DSA Topic 2 counted the moves. (DSA Topic 11 meets pop(0) again for queues; here it is only the wrong end of a stack.)
The point that is specific to stacks is that the cost follows the depth. Run 10^5 mixed push/pop operations (seeded, about half pushes) on two workloads:
- Shallow: depth capped at 10, like a bracket checker on shallow input.
- Deep:
10^4pushes first, then mixed operations that keep the depth near10^4.
For each workload run a front-topped and an end-topped stack. Print the counted shifts of the front version beside the times of both. Conclude from the printed numbers whether the wrong end shows on shallow work and on deep work.
This question previews DSA Topic 12 (linked lists) and uses only the one idea a stack needs. A node holds a value and a reference to the node below it. Push makes a new node whose below is the old top; pop moves the top down one node. Nothing is ever resized, so every operation is O(1) in the worst case (a list's append is O(1) only amortised).
Write class _Node (with __slots__) and LinkedStack with push, pop, peek, __len__. Trace 5 pushes and 3 pops by printing the chain from top to bottom after each, and fuzz it against a list on 10,000 seeded operations, empty pops included.
Build the same stack interface two ways, ListStack (a list with its top at the end) and NodeStack (linked nodes, previewing DSA Topic 12). Using tracemalloc, measure the bytes per item of each after 10^5 pushes of the same object. Then best_of 3 times for 10^6 pushes and 10^6 pops through each class, plus a bare list.
Print both ratios and conclude from them. Why is a node stack bigger? Its one advantage (several versions sharing the part below) comes back later in the topic.
Write the stack the way C or Java would: a preallocated list [None] * capacity and an integer size (the count of items, which is also the next free slot). Pushing onto a full stack raises StackOverflowError, and popping an empty one raises StackUnderflowError; define both and catch them.
pop writes None back into the freed slot so the item can be collected (Python frees an object when its last reference goes; a C version would free it). Show this with a class that counts how many instances are alive, popping with and without the clearing step. State the costs: every operation is O(1) in the worst case, but the space is O(capacity) whether the stack is used or not.
Pushing items and then popping them all gives them back reversed, because the last one in is the first one out. Reverse a list, a string and the words of a sentence with a stack, and say in a sentence why the order flips.
For a list in memory, slicing [::-1] and reversed() do the job faster; DSA Topic 2 printed the reversal cost table (hand loop, .reverse(), [::-1], list(reversed())) with the space of each. The case where only a stack works is a one-pass input, such as a generator of words. Show that values[::-1] raises TypeError (not subscriptable) and reversed(gen) raises TypeError (not reversible), while push-all then pop-all succeeds. State the space: the stack is O(n) because the input cannot be read twice.
With only ( and ), every item on a stack would be the same (, so the stack's height says everything: a counter is enough. The string is balanced iff the counter never goes below 0 and ends at 0.
Write check_parens(s) returning ("ok",), ("unexpected", i, ")") for the first ) with nothing open (0-based index), or ("open", k) when k openers are left at the end. A counter knows how many are open but not where; positions need a real stack, which comes after multiple bracket kinds.
Check it against the pair-deletion oracle (delete adjacent () until none remain; balanced iff empty) over every () string up to length 16, and check the unexpected index against deletion on prefixes up to length 10.
With ()[]{} a closer must match the most recent unclosed opener, so the openers go on a stack; every other character is ignored. Write balanced(s) returning True or False.
First show that a depth counter (which adds 1 for any opener and subtracts 1 for any closer) accepts ([)], and that the stack rejects it. Then check balanced against the pair-deletion oracle (delete adjacent matched pairs until none remain) over every ()[]{} string up to length 6, and on a few strings with other characters mixed in. State the time and space.
A yes/no answer is not enough for an editor: it must say where. Push (opener, index) pairs. Write check_brackets(s) returning one result shape (0-based indices), used for the whole topic:
("ok",)("unexpected", i, ch): a closer atiwith nothing open("mismatch", i, ch, j, opener): a closer atiwhose partner is not on top;jis the opener on top("unclosed", j, opener): openers left at the end; report the top of the stack, the innermost one, which should have closed first
It stops at the first error. Print each case with a caret line under the text and a 1-based line:col. Fuzz: the result is ("ok",) exactly when pair deletion says balanced, and every error agrees with a brute force that runs the deletion on (char, index) pairs: the first error is the smallest i whose prefix s[:i + 1] still contains a closer after deletion.
A bracket checker that reports i = 412 is useless to a person editing a file; they need line:col. Do not make a second pass over the text (and no splitlines): count newlines during the same scan that drives the stack. Keep line and col (both 1-based) as running counters, reset col to 1 after each "\n", and store (opener, index, line, col) on the stack so that an opener's position is known when it is reported later.
Write check(text) returning (result, places). result is the topic's one result shape: ("ok",), ("unexpected", i, ch), ("mismatch", i, ch, j, opener) or ("unclosed", j, opener), where j is the opener on top of the stack (the innermost). places is a tuple with one (line, col) per index named in result (the closer first, then the opener). Print messages such as 3:14: unexpected ] for the edge cases: an error on the first character, one right after a newline, and one on a last line with no final newline. Fuzz check against an oracle that computes line:col from the index with str.count and str.rfind, and against pair deletion for ok/not ok.
"abbaca" becomes "ca": delete a pair of equal neighbours, and repeat while one exists ("abbaca" -> "aaca" -> "ca", because deleting bb makes the two as neighbours).
Write naive(s, stats), which rescans the string and rebuilds it after every deletion, counting comparisons of neighbours. Then write with_stack(s): if the next letter equals the top, pop; otherwise push; "".join(stack) at the end. Count the naive version's comparisons on the nested input "ab" * k + "ba" * k (the pair to delete is in the middle every time) for four sizes, and the stack's pushes and pops beside them. Fuzz the two against each other on strings over "ab" and "abc" from length 0.
In "ab#c" the # deletes the letter before it, so the typed text is "ac". A backspace is a pop, and a backspace on empty text does nothing ("a##c" is "c").
Write typed(s, stats) with a stack, returning the text (and recording the stack's peak size), and same_text(s, t) using it. DSA Topic 4 compared two typed strings from the right with two pointers in O(1) space: write that compactly as same_text_pointers(s, t, stats) and use it as the oracle. Fuzz them on strings over "ab#" from length 0, then compare counted steps and extra space on two strings of 10^5 characters. State which version can also give you the typed text.
Postfix (reverse Polish) notation puts each operator after its operands: 3 4 + 2 * means (3 + 4) * 2. Scan the tokens left to right: a number is pushed; an operator pops the right operand first, then the left, and pushes the result. Division is exact, using fractions.Fraction, so no float appears.
Write eval_postfix(tokens) for + - * / (a list of strings). Errors carry the token's index: too few operands for an operator, numbers left over (reported at index len(tokens)), an unknown token. Print the stack after each token for 3 4 + 2 *. Fuzz it: a small generator builds a random nested tuple (op, left, right) (the nested expression form of DSA Topic 8; the general idea is a tree, DSA Topic 13) and writes it as infix and as postfix; eval on the infix text (numbers wrapped as F(3), under {"__builtins__": {}, "F": Fraction}) is the oracle, and a division by zero must raise ZeroDivisionError in both.
One expression has three notations. Infix (3 - 4 - 5) needs precedence rules and brackets. Prefix (Polish: the operator comes first, - - 3 4 5) and postfix (3 4 - 5 -) fix the order of operations with neither. Evaluate prefix by scanning right to left with one stack: this time the first operand popped is the left one.
Show that 3 - 4 - 5 and 3 - (4 - 5) differ in infix only by brackets, and in prefix and postfix by token order. A generator builds each random nested tuple (op, left, right) (the nested expression form of DSA Topic 8; the general idea is a tree, DSA Topic 13) in every form at once (fully bracketed infix, plain infix, postfix, prefix). Write both evaluators (/ is exact, with Fraction) and fuzz: the four forms must agree with eval on the infix text, including when it divides by zero. Print how many brackets each form needs on average.
Dijkstra's shunting-yard turns infix into postfix with one operator stack. Numbers go straight to the output. An incoming operator first pops every operator on the stack with higher precedence, or with equal precedence when the incoming one is left-associative, and sends it to the output; then it is pushed. At the end the stack empties into the output. Use only + - * / (precedences 1, 1, 2, 2), no brackets yet.
Write a character-loop tokenize(text) producing (kind, text, pos) tuples and shunting_yard(tokens, trace=False), using exactly this pop rule: while ops and ops[-1] != "(" and (PREC[ops[-1]] > PREC[op] or (PREC[ops[-1]] == PREC[op] and op not in RIGHT)):. Print a (token, output, stack) table for 3 + 4 * 2 - 1. Evaluate the postfix with a stack (exact Fraction division) and fuzz it against eval on random flat expressions. Assert that each operator is pushed once and popped once.
Add brackets to shunting-yard. An opening bracket is pushed and blocks popping (the pop rule stops at (). A closing bracket pops operators to the output down to its opening bracket, which is discarded. A ) with no ( open, or a ( still open at the end, is an error reported with its position in the topic's bracket shape: ("unexpected", i, ")") or ("unclosed", j, "(") with j the innermost open bracket.
Keep the operator stack of strings and a second small stack of the positions of the open (. Trace (3 + 4) * (2 - 1). Fuzz against eval on generated bracketed expressions (fully bracketed and minimal forms, plus ((7))). Then corrupt valid texts by deleting or inserting a bracket, and compare the reported error with a brute-force position found by pair deletion on (char, index) pairs.
Every action pushes onto a history stack what it takes to reverse it. Appending x to a list records a pop. Setting a key records its old value, or a delete if the key was new. Deleting a key records the removed value so it can be set again. Undo pops one record and applies it. A delete of a missing key is not an action and records nothing.
Write class Settings with a list items, a dict cfg, and methods do(action) and undo(). Undo with an empty history does nothing and says so (returns False). Test "was the key present" with in, not .get, because the old value may be None. Trace a state through 6 actions and 4 undos, then fuzz 3,000 seeded operations against a model that keeps a snapshot of the state before every action.
Two stacks can share one fixed list: stack 0 grows from the left end, stack 1 grows from the right end, and the stacks overflow only when their tops meet (left + right == capacity). Two separate halves of capacity // 2 slots each waste room whenever one stack is fuller than the other.
Write class TwoStacks(capacity) with push(which, x) and pop(which), raising StackFull and StackEmpty, and class Halves(capacity) with the same interface and two fixed halves. Count the pushes accepted before the first overflow, for capacity 1,000, on three push-only workloads: strictly alternating, 50/50 at random, and 90% to stack 0. Run the random workloads over 20 seeds and print the minimum, average and maximum. Assert only what the printed numbers pin down. Fuzz TwoStacks against two plain lists, including capacity 0. Every operation is O(1).
A toy program is a dict from a function name to a list of steps: "call g", "work 3" (takes 3 time units) or "fail". Run it with a stack of frames Frame(name, pc), where pc is the index of the next step. A call pushes a frame; reaching the end of a function pops it, and the caller resumes at its saved pc (the return point). DSA Topic 8 showed Python's own frames and turned recursion into a loop; this program is not Python, and the stack is the whole interpreter.
Write run(program, entry, max_depth, trace=False) returning ("done", clock, deepest), ("failed", clock, lines) with a traceback (outermost first, innermost last, the way Python prints it), or ("overflow", max_depth). Print the stack at each call and return for a small program, the traceback for a failing one, and an overflow from a function that calls itself. Check clock and deepest against a recursive oracle on 500 seeded random programs, including a function with no steps.
For each item of a list, find the index of the first item to its right that is strictly larger, or -1 if there is none. For [2, 7, 3, 5, 4, 6, 8] the answer is [1, 6, 3, 5, 5, 6, -1] as indices.
- write the brute force
next_greater_truth(a): scan right from every index. Count comparisons, and state its complexity. - write
next_greater(a)with a monotonic stack of indices that are still waiting for an answer. Their values never increase from bottom to top (equal values wait together). A new item pops every waiting index with a smaller value, because the new item is that index's answer, and then waits itself. Return the answer list and the number of pushes and pops, and assertpops <= pushes == n. - trace
[2, 7, 3, 5, 4, 6, 8], printing the stack of indices after each item. - fuzz against the brute force on the named edge shapes: empty, one item, all equal, increasing, decreasing, zigzag, few distinct values (0 to 2) and random. Start at size 0.
A while loop inside a for loop looks like O(n^2). Show that the monotonic stack for the next greater element is O(n).
- write
next_greater_counted(a)returning the answers pluspushes,pops,comps(every test of thewhilecondition against an item) andworst_step(the most pops in a single iteration). - run it on random, increasing, decreasing and zigzag inputs with n = 1,000, and print the counts. Assert
pushes + pops <= 2neach time, with the argument for why in a comment. - build an input where one step pops
n - 1items (a decreasing run, then one large item). Print that worst single step beside the amortised pops per item. - compare counted comparisons against the O(n^2) brute force on a decreasing input for n = 500, 1,000 and 2,000 with
best_oftimes beside them, and once more at n = 4,000 by count only. Then run the stack alone at n = 10^4 and 10^5. Conclude from counts, not from clock verdicts.
Cite DSA Topic 2 (the inner pointer only moves forward) and DSA Topic 5 (each window edge moves at most n times): the same argument.
For each day, how many days must you wait until a strictly warmer day, or 0 if there is none? For [73, 74, 75, 71, 69, 72, 76, 73] the answer is [1, 1, 4, 2, 1, 1, 0, 0].
Write days_until_warmer(temps) with a monotonic stack. The stack holds the indices of days still waiting, because the answer is a difference of two indices and a stack of temperatures alone could not give it. The pop condition's comment must say why an equal day does not answer. Write days_until_warmer_truth as the O(n^2) scan, fuzz the two against each other with few distinct values (where ties are common). Give the time and space.
Write an online class with next(price): it returns the span of today's price, the number of consecutive days ending today (today included) whose price is <= today's. For prices [100, 80, 60, 70, 60, 75, 85] the spans are [1, 1, 1, 2, 1, 4, 6].
NaiveSpannerstores all prices and walks back one day at a time, counting steps. Show that on rising prices it costs O(n) per call and O(n^2) in total.StockSpannerkeeps a stack of(price, span)pairs. A popped day's span is added to today's, so the walk jumps over whole spans. State the amortised cost per call, and print the worst single call too.- Fuzz both against each other on few-distinct prices, starting with zero calls.
Design a stack with push, pop, top and get_min, all O(1). The idea: each entry stores (value, the minimum of everything at or below it), so after a pop the new top already knows the minimum.
- write
NaiveMinStack, whoseget_minismin(self.items). Count the items it scans and show that n pushes each followed by aget_minscan O(n^2) items. - write
MinStackwith the paired entries. Every method on an empty stack raisesIndexErrorwith a message naming the operation. - trace a short run that pushes the minimum twice, so you can see that popping one copy leaves the other.
- fuzz 10,000 seeded operations against a plain list model, using only values 0 to 3 so duplicate minimums are common.
State time and space for each method.
Next greater, previous greater, next smaller and previous smaller are one algorithm with two choices: the scan direction and the comparison in the pop condition.
- write
nearest(a, side, want)withsidein"next"or"prev"andwantin"greater"or"smaller". It returns the index of the nearest strictly greater (or smaller) item on that side, or-1. Assertpops <= pushes == n. Say strict in the docstring; ties are a later question. - print a table of the four, each with its scan direction, the order kept on the stack and the pop condition. Build the table from the same data the function uses, so it cannot disagree with the code.
- show that the previous greater item can be read in the same left-to-right pass as the next greater: it is the index on top after popping, or that index's own previous greater if the top equals the new item.
- fuzz all four against brute force
nearest_truthon the named edge shapes, starting at size 0.
The list is circular: after the last item comes the first, so an item's next greater item may lie to its left. For [1, 2, 1] the answer (as values) is [2, -1, 2]; for [5, 4, 3, 2, 1] it is [-1, 5, 5, 5, 5]. Return indices, with -1 when no item in the whole circle is strictly greater.
Write next_greater_circular(a): scan i = 0 .. 2n - 1 and read a[i % n]. Push an index only during the first pass; the second pass only answers. Assert the pushes and pops stay at most n each. Compare against next_greater_circular_truth, which scans n - 1 steps forward with wrap-around, on every edge shape (empty, one item, all equal, increasing, decreasing, zigzag, few distinct, random). Give time and space, and say why the second pass cannot add to the stack.
You have a list nums of distinct values and a list queries whose values all come from nums. For each query, return the first larger value to the right of that value in nums, or -1. Write next_greater_for_queries(nums, queries).
- One monotonic pass fills a dict from each value to its next greater value (DSA Topic 7); then each query is a dict lookup.
- Count the steps against answering each query by scanning (find the value, then walk right). Print the counts for n = 3,000 and q = 1,000 and compare O(n + q) with O(n * q).
- The docstring must say the values are distinct. Show the duplicate case going wrong: a value-keyed dict cannot tell two copies of a value apart. Print the wrong answer beside the truth, and assert they differ.
Each price is reduced by the first later price that is less than or equal to it, if there is one. For [8, 4, 6, 2, 3] the final prices are [4, 2, 4, 2, 3]. This is the next smaller-or-equal item, so the pop condition pops while the top's price is >= the incoming one: an equal later price counts.
Write final_prices(prices) with a monotonic stack of indices and final_prices_truth with the O(n^2) scan. Fuzz them with few-distinct prices (starting at size 0). Say in the pop-condition comment why an equal later price must pop. Give time and space.
Bars of width 1 stand side by side with the given heights. Find the area of the largest rectangle that fits under them. For [2, 1, 5, 6, 2, 3] it is 10 (the bars 5 and 6, height 5, width 2).
- brute force
largest_rectangle_truth(h): for every pair(i, j)keep a running minimum height. State its complexity and count its steps. - the insight, in a comment: the best rectangle that uses bar
iat its full height runs from just after the previous strictly smaller bar to just before the next strictly smaller bar. largest_rectangle(h)findsleft[i]andright[i]with two monotonic passes (a-1and annstand for "no smaller bar"), and the area ish[i] * (right[i] - left[i] - 1). Handle the empty list.- fuzz against the brute force on the edge shapes, then count the work for n up to 10^5 (brute force only to 4,000). Conclude from the counts.
The two-pass histogram solution (previous smaller and next smaller, each with its own stack) can be folded into one left-to-right pass. Keep a stack of indices whose heights strictly increase from bottom to top. When bar k is popped at index i, then i is the first bar to its right that is not taller (its next smaller bar, up to ties), and the new top of the stack is the nearest bar to its left that is shorter (its previous smaller, or -1 when the stack is empty). So the widest rectangle of height h[k] spans i - top - 1 bars, and it is known the moment k is popped.
Write largest_rect(h, stats=None, trace=False) that returns the best area, with a virtual sentinel bar of height 0 at index len(h) that flushes the stack at the end (it is never pushed). Use the pop condition h[stack[-1]] >= cur and say in a comment why the tie rule is safe: an equal bar popped early gets a narrower rectangle, and the equal bar that popped it still covers the full width. Write the two-pass largest_rect_two_pass(h) (same tie care) and an O(n^2) largest_rect_truth(h). Trace [2, 1, 5, 6, 2, 3]. Argue in a comment that every bar is popped exactly once, so every candidate rectangle is considered, and assert pops == pushes == n (fuzz includes size 0). Fuzz all three on the edge shapes (empty, one bar, all equal, increasing, decreasing, zigzag, few distinct values 0..2, random). Then compare pushes, pops and the peak memory (tracemalloc) of the two versions at n = 50,000 on increasing and decreasing input, and print the numbers.
Water over a row of bars can be counted in layers instead of columns. Keep a stack of indices whose heights never increase from bottom to top. When a taller bar x = h[i] arrives, pop the floor f. If a left wall remains on the stack, the water between that wall and i, above the floor and below the lower of the two walls, is (min(h[left], x) - h[f]) * (i - left - 1). If no wall remains, the water spills and nothing is added. Keep popping while the new top is also lower than x.
DSA Topic 4 solved this with two pointers and with two scans (prefix and suffix maxima): write both compactly as water_two_pointers(h) and water_two_scans(h), add water_stack(h), and an O(n^2) water_truth(h) that sums min(max left, max right) - h[i] by scanning. Trace [3, 0, 1, 0, 2, 0, 4] layer by layer. Fuzz all four (size 0 included, few-distinct values, flat plateaus). Then compare counted steps and extra space at n = 1,000: the stack needs O(n) space, two pointers O(1), and two scans two arrays of n.
Shunting-yard sends operators to an output list, and a second loop evaluates that postfix list. You can skip the list. Keep two stacks, one of values and one of operators, and whenever shunting-yard would send an operator to the output, apply it right away: pop two values (right operand first), compute, push the result. Brackets are handled on the operator stack: ( is pushed and blocks popping, and ) applies operators down to its (.
Write tokenize(text) (a character loop producing (kind, text, pos)), and evaluate(text, trace=False, stats=None) that returns a Fraction (exact /) using exactly the pop rule while ops and ops[-1] != "(" and (PREC[ops[-1]] > PREC[op] or (PREC[ops[-1]] == PREC[op] and op not in RIGHT)):. A ) with nothing open raises BracketError(("unexpected", i, ")")); a ( left open raises BracketError(("unclosed", j, "(")) for the innermost one; empty text raises ValueError. Trace 2 * (3 + 4) - 5 showing both stacks after each token. Fuzz against eval on generated expressions (fully bracketed and minimal forms, plus ((7))), counting divide-by-zero as an agreed result. Assert that every operator is pushed once and popped once.
8 - 3 - 2 means (8 - 3) - 2 = 3, but 2 ^ 3 ^ 2 means 2 ^ (3 ^ 2) = 512, not (2 ^ 3) ^ 2 = 64. Add ^ (written ** in Python) with precedence 4 and mark it right-associative: RIGHT = {"^"}. The one pop rule while ops and ops[-1] != "(" and (PREC[ops[-1]] > PREC[op] or (PREC[ops[-1]] == PREC[op] and op not in RIGHT)): already does the job, because an incoming ^ does not pop a ^ already on the stack.
Write evaluate(text, right=RIGHT) (two-stack, one-pass, exact Fraction; the caller can pass another right set) and pop_table() that prints, for every pair of operators (stack top as row, incoming as column), whether the rule says pop or push. Show 2 ^ 3 ^ 2 evaluates to 512 and the same code with right=set() to 64. Then fuzz against eval with ^ written **, on generated expressions in fully bracketed and minimal forms, where every exponent is a literal 0..3 or a short tower of such literals. An expression that divides by zero must agree in both.
Extend shunting-yard with max(a, b, ...), min(a, b, ...) and abs(x). A function name is pushed onto the operator stack; its ( sits above it. A comma pops operators down to the nearest ( (so each argument is finished), and the closing bracket pops the rest, discards the (, pops the function name and writes it to the output as name/count, e.g. max/3. The count of arguments comes from a separate stack of counters, one record per open bracket (a call record, or one with name None for a plain bracket).
Write tokenize(text) (names are letter runs), to_postfix(tokens) returning ("ok", postfix) or an error tuple naming the position (0-based): ("arity", pos_of_name, name, count) for the wrong number of arguments (abs takes exactly 1, max and min at least 1), ("comma", pos) for a comma outside a call, ("empty", pos) for an empty argument or empty text (at the offending comma or ); ("empty", 0) for empty text), ("unexpected", pos, ")"), ("unclosed", pos, "(") (innermost), ("unknown", pos, name) and ("bare", pos, name) for a function name not followed by (. Write eval_postfix(post), with name/count popping count values. Show the postfix of max(1, 2 + 3, abs(4 - 9)). Check a list of bad inputs against their expected tuples, then fuzz valid generated expressions (nested calls, brackets, /) against eval with the three functions whitelisted.
Turn a postfix list (binary operators + - * / ^ only, numbers as atoms) into infix text with the fewest brackets. Keep a stack of (text, precedence); an atom has precedence 9. When an operator op with precedence p arrives, pop the right operand and then the left, and wrap an operand in brackets by this rule:
- a left operand needs brackets if its precedence is lower than
p, or equal whenopis right-associative (^); - a right operand needs brackets if its precedence is lower than
p, or equal whenopis left-associative.
Write to_infix(postfix), which raises ValueError for an empty or malformed list (size 0 included). Write to_postfix(text) (shunting-yard with brackets, character-loop tokeniser) and check two things on seeded random expressions: parsing the infix back gives exactly the same postfix, and removing any one bracket pair changes that postfix, so no pair is spare. Also count how many brackets a fully bracketed rendering would have used and print it beside the minimal count.
HTML-like tags nest exactly like brackets. <b> opens, </b> closes, <br/> closes itself (nothing to push), and names compare case-insensitively. Text between tags is ignored. No re and no html.parser: find each tag with a character loop (< up to the next >), recording its name and the position of its <.
Write tokenize_tags(text) returning (kind, name, pos) tuples with kind "open", "close" or "self" (names lower-cased), and check_tags(text) with a stack of (name, position) returning the topic's result shape: ("ok",), ("unexpected", i, name) for a closer with nothing open, ("mismatch", i, name, j, opener) for a closer whose partner is not on top (j and opener describe the top), and ("unclosed", j, name) for the innermost tag left open. A < with no > gives ("badtag", i); an empty name is also ("badtag", i). The checker stops at the first error. Attributes and entities are out of scope, so a bare < inside text is reported as ("badtag", i). Fuzz against pair deletion: map each tag name to a bracket pair, run the deletion on (char, position) pairs, and compare. Generate mostly-balanced documents, mutated by one change, so all four outcomes occur.
With only +, -, brackets and unary signs there is no precedence to resolve, so two stacks are overkill. Keep a running result and a pending sign for the next operand, and a single stack for brackets. Read operands and signs with a character loop: a number adds sign * number to the result and resets the sign to +1; after an operand, + or - is a binary operator and sets the sign; where an operand is expected, - flips the pending sign (so 5 - -3 and --3 work) and + changes nothing; ( pushes (result, sign) and starts afresh with result 0 and sign +1; ) pops and combines result = saved_result + saved_sign * inner. Numbers may have several digits; empty text raises ValueError.
Write calc_signs(text, stats=None). Also write calc_shunting(text, stats=None): shunting-yard with a prefix neg operator (precedence 3, pushed without popping anything) and a postfix evaluator. Fuzz both against eval on generated expressions like -(1 - (2 + -3)). Compare them by counted stack operations (pushes plus pops on every stack in use), assert the signs-only count never exceeds the shunting-yard count, and print the totals.
3[a2[c]] decodes to "accaccacc": a count, then a bracketed group repeated that many times. Counts can have several digits (10[ab]). Write a character loop scan(s) that returns tokens ("lit", ch), ("open", count) and ("close",) and raises ValueError with the position for a bracket with no count, a count not followed by [, a stray ], a missing ], or any character that is not a letter, digit or bracket.
Write decode(s, cap): at [ push (count, text so far) and start a new string; at ] pop and append the inner text count times. The output can be exponentially long: write decoded_length(s) which computes the length with a stack of (multiplier, length so far) and builds no text, and make decode call it first and raise TooLong when the length exceeds cap. A 0[...] group contributes nothing, so decode must skip its contents without building them (0[ followed by a deep 9[ nest must not hang). A missing ] raises ValueError naming the position of the innermost unclosed group's count. Show that "2[" * 20 + "a" + "]" * 20 is refused instantly and that decoded_length of a depth-40 nest of 9[ is exactly 9^40, far past a 64-bit integer (Python ints are unbounded; C or Java would overflow). Fuzz decode against a brute force that expands the innermost bracket again and again until none is left, starting at size 0, and check decoded_length(s) == len(decode(s)).
Simplify a Unix path with a stack of components. Split on /; ".." pops a component (never above the root, so /.. stays /); "." and empty parts (from // or a trailing /) are skipped; anything else is pushed (... and a..b are ordinary names). Join with / and start with /. Write simplify(path), which treats any input as a path from the root and always returns an absolute path.
Compare it with posixpath.normpath (the POSIX flavour on every OS) on seeded random paths and print where they differ. First print what normpath gives for "", "//a", "///a" and "/..". Then classify every difference by cause and assert that the differences have only the causes you found: for paths that do not start with /, normpath stays relative (and keeps leading .., and returns "." for an empty result), and POSIX keeps exactly two leading slashes. Everywhere else the two must agree.
Distinct items are pushed onto a stack in a fixed order (pushed), and between pushes the program may pop. Someone claims the items came off in the order popped. Is the claim possible?
- write
valid_pop_order(pushed, popped): push each item, then pop while the top equals the next item the claim wants. The claim is valid iff the stack ends empty. Say in a comment why popping as soon as the top matches is safe: waiting would only bury that item under later pushes. - print one valid and one invalid claim for five items, with the stack that is left stuck in the invalid case.
- build an oracle that does not use the pop-as-soon-as-it-matches rule: the set of pop orders a stack can produce once per n, by filtering
itertools.product("PO", repeat=2 * n)down to the sequences with n pushes that never pop an empty stack and simulating each one. Then, for n = 0..7, test every permutation fromitertools.permutationsagainst the oracle and against your function, and count the valid ones. Compare the counts with the Catalan numbersC(2n, n) // (n + 1).
A single-threaded program writes a log of lines "id:start:t" and "id:end:t". An end at t includes time unit t, so a function that starts and ends at t = 3 ran for exactly one unit. Calls nest, and a function may call itself. This stack is the program's call stack: a start is a call that pushes a frame, an end is a return that pops it, and the top is the function running now. The exclusive time of a function is the time it spent running its own code, not counting the time of the calls it made.
- write
exclusive_time(n, log). The stack holds the ids that are running. Astartattcharges the function on top for the units up tot - 1, then pushes. Anendattcharges the topt - prev + 1units, then pops. Return("ok", times). - validate the log. An
endmust match the function on top, and the first bad line is returned by its 1-based number as("bad", line, reason). Cover a malformed line, anendwith nothing running, anendfor the wrong function, time running backwards, and a function that never ends (report the line of itsstart). - build a generator that writes a random log together with the true per-function times, and a brute force
exclusive_brutethat walks the log one time unit at a time and charges the unit to whoever is on top. Fuzzexclusive_timeagainst both, starting at the empty log. - fuzz the errors. Corrupt valid logs (change an id, delete a line) and compare against the bracket oracle: delete adjacent
start f/end fpairs until none remain; the log is valid iff nothing is left, and the first error is the smallest line whose prefix still holds anendafter deletion.
Asteroids sit on a line in the given order. The sign is the direction (positive moves right, negative moves left) and the size is the absolute value. All move at the same speed, so two meet only when a right-mover is immediately left of a left-mover. The smaller one explodes; if they are equal, both do. Return the asteroids that survive.
- write
asteroid_collision(a)with a stack of survivors so far. An incoming left-mover pops every smaller right-mover on top, stops at a larger one (and dies), and is destroyed with an equal one. Countpushesandpopsand assertpops <= pushes <= n. - write the brute force
collide_truth: find the leftmost adjacent pair(+, -), resolve it, and repeat until none is left. It is O(n^2) in the worst case. - fuzz the two against each other on empty input, one asteroid, all positive, all negative, all equal sizes, and random signed sizes 1..4 (zero is not an asteroid).
Delete every run of k equal neighbours from a string, and keep deleting as the pieces on either side join up, until none is left. (For k = 2 this is the adjacent-duplicates question from earlier in this topic; here k is a parameter, so a count has to live on the stack.)
- write the naive
remove_k_naive(s, k, work): scan from the left for a run ofk, cut it out with a slice, and rescan from the start. Add towork[0]one for every character compared andlen(s)for every slice, because a slice copies.kis at least 2. - write
remove_k(s, k)with a stack of[letter, run length]. A letter equal to the top bumps its count, and a count that reacheskpops the entry. - on the nested string
abcabc...cbacba(a left half that cycles throughabcfollowed by its mirror image), count the naive work at n = 200, 400, 800, 1600 and compare it with the stack's n steps. Print the times withbest_ofbut give no clock verdict; the counts carry the point. - fuzz with
kin 2..4 on strings overabandabc, starting at length 0, against the naive version as the oracle.
The usual min-stack stores a (value, minimum so far) pair for every item: two slots per item. A second stack that holds only the minimums does better. Push x onto it when x <= its top (the <= keeps duplicate minimums), and pop it when the popped value equals its top.
- write
MinStack(a data list plus aminslist) andPairStack(the pairs version) withpush,popandget_min. Each operation is O(1). - count stored slots (pairs:
2n; two stacks:n + len(mins)) for 1,000 pushes of an increasing sequence, a decreasing one, an all-equal one, and a random permutation. For the random case averagelen(mins)over 20 seeds and print it next to the harmonic numberH_n, with the smallest and largest single seed. Say what you see in a comment. - fuzz push/pop/get_min against
min(data)on few-distinct values, with empty-stack cases.
A stack supports push(x), pop() and increment(k, v), which adds v to the bottom k items (all of them if the stack is smaller than k; nothing if k <= 0). pop on an empty stack returns None.
- write
NaiveIncStack, whoseincrementloops over the bottomkitems. Count every item it touches inself.touches. - write
LazyIncStack. Keep a listincbeside the values.increment(k, v)addsvtoinc[min(k, size) - 1]only.poptakes the top, returnsvalue + inc[top], and passesinc[top]down toinc[top - 1], because everything below the top was also covered by that increment. Count eachincwrite as one touch. - run the same workload on both: push 1,000 items, call
increment(10**9, 1)1,000 times, then pop everything. Print the touches and assert the popped values agree. - fuzz both against each other with
kfrom -1 to 8 on stacks of 0 to 6 items.
Build a stack whose get_max(), get_min() and get_sum() are all O(1) after any push or pop. Each entry stores the value together with the maximum, minimum and sum of everything at or below it. Queries on an empty stack behave like the built-ins: max([]) and min([]) raise ValueError, and the sum of nothing is 0.
- write
StatsStack. - count the items a recompute-every-time version touches on a workload of 500 pushes each followed by the three queries, against the touches of
StatsStack, and print both. - fuzz against recomputing
max,minandsumof a plain list, with the empty stack included. - say in a comment what this design cannot do. Removing the maximum from the middle of the stack needs a linked list (DSA Topic 12) or a heap (DSA Topic 15). Both are named only.
A text editor keeps two stacks, undo and redo. Doing an action pushes it on undo and clears redo, because those redo steps no longer follow from the text on screen. Undo pops the last action, reverses it, and pushes it on redo. Redo pops from redo, applies it again, and pushes it back on undo.
- write
Editorwith a text buffer,type(s)(appends),erase(n)(remove up toncharacters from the end; an erase that removes nothing is not recorded),undo()andredo(). Store each action as a small tuple that carries what it needs to be reversed:("type", s)and("erase", removed_text).undo()andredo()returnFalsewhen their stack is empty. - trace a session: type
"ab", type"cd", undo twice, redo once, then type"X". Print the buffer and both stacks after each step, so the cleared redo stack is visible. - model-based fuzz: 2,000 seeded sequences of do, undo and redo. The model is a list of every state reached plus an index; undo moves the index back, redo forward, and a new action truncates the list after the index and appends. Compare the buffer and the return values after every step.
- state the cost of each operation in a comment: O(1) stack work, plus a buffer update that costs O(len(text)) because a
stris immutable and every+=or slice copies it.
There are two ways to undo. A command stores the inverse of each action (what was inserted, what was removed, and where). A snapshot stores a copy of the whole state before each action, made with copy.deepcopy. Compare them on a 10,000-byte buffer (a bytearray, a mutable string) after 2,000 seeded edits, each inserting or deleting 1 to 5 bytes at a random position.
- write
run_commands(buf, edits)andrun_snapshots(buf, edits), each applying every edit and keeping its undo history. Then undo everything in both and assert the buffer is back to the original. - measure with
tracemallocthe memory the history retains (bytes after minus bytes before, with the buffer itself outside the measurement) for each style, and print the ratio. Assert the snapshots hold more than 10 times as much. - time "apply 2,000 edits, then undo all" with
best_of(min of 3) for both and print the times and ratio. Give no clock verdict; the memory counts carry the point. - show an action a command cannot easily reverse:
lowercase_all, which loses the original capitalisation. An inverse command must record what the action destroyed (here, which positions were capitals); for actions that rewrite most of the state, that record is as large as a snapshot, so a snapshot is simpler. Print the snapshot undo restoring it. Say when snapshots are the right choice.
A browser keeps two stacks, back and forward, plus the current page. Visiting a page pushes the current one onto back and clears forward. back(k) and forward(k) move at most k pages, and return the current page afterwards (None before the first visit). History is capped: only the newest c pages can be reached by going back.
- write
NaiveBrowser(c): after each visit, ifbackhas more thancpages,del back[0]. Each such delete shifts the rest, so countlen(back) - 1moved items per delete inself.moved. - write
LazyBrowser(c): letbackgrow to2cand only then cut it down to the newestcpages, counting thoseccopied items inself.moved. Keep a counterreachof how many pagesback(k)may still use, so the visible history is exactly the same as the naive one's. - run 20,000 visits with
c = 1000on both. Print the moved counts, and assert the two browsers end on the same page. - fuzz both against a model, a list of pages with an index, using
cin 1..4 andkin 0..5, checking the current page after every step. Start from a browser that has never visited anything. collections.deque(maxlen=c)does the capped history directly; it is DSA Topic 11, named only.
Add up the minimum of every contiguous subarray. For [3, 1, 2, 4] the 10 subarrays have minimums 3, 1, 1, 1 (starting at index 0), 1, 1, 1 (index 1), 2, 2 (index 2) and 4, and their sum is 17.
- write
sum_mins_brute(a): from every start, extend right with a running minimum. Return the sum and the number of inner steps, and state the complexity. - count by contribution. Item
iis the minimum of(i - left) * (right - i)subarrays, whereleftis the previous strictly smaller index (-1if none) andrightis the next smaller-or-equal index (nif none). One side is strict and the other is not, so a subarray whose minimum appears twice is counted exactly once, by its rightmost minimum. Writesum_mins(a), which finds both bounds in one stack pass and returns(total, pushes, pops)withpops <= pushes == n. - fuzz
sum_minsagainst the brute force on the named edge shapes (empty, one item, all equal, increasing, decreasing, zigzag, few distinct values 0 to 2, random), starting at size 0. Then count the work forn = 2,000(brute force) againstn = 10^5(stack). Say in a comment what Python ints do that C ints do not (Rule 7).
The range of a subarray is its maximum minus its minimum. Add up the range of every contiguous subarray.
Because max - min splits cleanly, the total is (sum of subarray maximums) - (sum of subarray minimums). Write:
sum_ranges_brute(a): from every start, extend right with a running maximum and minimum. Return the total and the inner steps.sum_mins(a)andsum_maxs(a): each finds its two bounds in one stack pass and returns(total, pushes, pops). The maximum version mirrors the tie rule: previous strictly greater, next greater-or-equal.sum_ranges(a): their difference. Four monotonic scans' worth of work (previous and next, smaller and greater) in two passes.
Fuzz on the named edge shapes including few-distinct values, starting at size 0. Count the work at n = 2,000 and n = 10^5.
Given a grid of 0 and 1 (a list of lists of ints), find the area of the largest rectangle that contains only ones.
- write
largest_in_histogram(h)using the two-pass previous/next smaller method, or the one-pass version: when barkis popped by a bar atiwithh[k] >= h[i], its rectangle spans from just after the new top of the stack to just beforei, and a height-0 bar at indexnpops everything left at the end. It returns(area, pushes, pops)and handles an empty list. - write
max_rectangle(grid). Row by row,heights[j]is the number of consecutive ones ending at this row in columnj. This is a running count (reset to 0 on a zero), not a DP table, so no later topic is needed. Each row is then a histogram. Handle zero rows and zero columns. - write
max_rectangle_brute(grid): test every rectangle in O(1) with the 2-D prefix sums of DSA Topic 6, for grids up to 12 x 12, and count the rectangles tested. - fuzz both with ones-density from 0.3 to 0.9, starting from shapes with 0 rows or 0 columns, and print the counted work for a 12 x 12 grid.
Find the length of the longest balanced substring (contiguous) of a string of ( and ). For ")()())" it is 4.
- write
longest_valid_brute(s): from every start, scan with a depth counter, stopping when the depth goes below 0. State the complexity. - write
longest_valid_stack(s). The stack holds indices and starts with-1as its base, the index just before the current candidate.(pushes its index.)pops; if the stack is now empty, pushias the new base; otherwisei - stack[-1]is the length of a balanced substring ending ati. - write
longest_valid_scans(s)in O(1) extra space: scan left to right counting opens and closes (reset when closes exceed opens; record2 * closeswhen equal), then scan right to left with the roles swapped. - check all three agree on every string of
(and)up to length 14. A DP version also exists; it is DSA Topic 21's and only named here.
Remove the fewest brackets from a string of (, ) and other characters so that the brackets balance, keeping every other character. For "a)b(c)d(" one answer is "ab(c)d".
Write min_remove(s): a stack of the indices of unmatched ( and a set of the indices of unmatched ) give exactly the characters to drop. Many outputs can be right (for "(a)b)" you may drop the ) at index 2 or the one at index 4, giving "(ab)" or "(a)b"), so the oracle checks properties, not one string:
- the result is balanced (use a counter);
- it is a subsequence of the input, with every non-bracket character kept;
- the number removed equals the brute-force minimum, found by trying removal counts 0, 1, 2, ... with
itertools.combinations(length at most 12).
Fuzz 1,500 seeded strings over "()ab" starting at size 0.
A string of (, ) and * is valid if every * can be replaced by (, ) or nothing so that the brackets balance.
- write
valid_brute(s): try all3^kreplacements of thekstars withitertools.product(fork <= 8). - write
valid_stacks(s): two stacks of indices, open brackets and stars. A)first matches an open bracket, otherwise a star, otherwise the string is invalid. At the end every open bracket left needs a later star, matched from the tops of both stacks. - write
valid_counter(s): track the lowest and highest possible depth (lo,hi). Name why it works: the set of reachable depths is an unbroken range. - check all three on every string of
()*up to length 7, then on seeded random strings up to length 14 with at most 8 stars.
Score a balanced string of ( and ) by these rules: () scores 1; AB scores A + B; (A) scores 2 * A. So "(()(()))" scores 6.
- write
score_rules(s), the oracle that applies the three rules directly (split into top-level pieces, recursion is fine here). - write
score_stack(s): a stack of partial scores.(pushes 0;)pops the inner scorevand addsmax(1, 2 * v)to the new top. - write
score_depth(s): the second view. Every()pair, an opener immediately followed by its closer, adds2^depth, wheredepthis the number of brackets enclosing it. - check all three on every balanced string up to length 14 (filter
itertools.product), and print the score of a few strings.
Does a list contain indices i < j < k with a[i] < a[k] < a[j]? ("1", "3", "2" is the shape of the values.) Return a bool.
has132_cubic(a): all triples, forn <= 200. Count the triples visited.has132_quadratic(a): for eachj, the bestiis the prefix minimum before it (DSA Topic 6), so onlykis searched.has132_stack(a): scan from the right with a non-increasing stack of indices and a valuethird, the largest value popped so far. Poppinga[stack[-1]] < xmeansxhas a smaller value to its right, sothirdalways has a larger value (the item that popped it) to its left. Anyx < thirdthen completes a pattern. Count pushes and pops.- fuzz all three on the edge shapes plus few-distinct values (equal values are not a pattern, because both comparisons are strict), starting at size 0, then count the work on a decreasing list of 200.
Given a string of digits num and an integer k, remove exactly k digits so that the number left is as small as possible. Return it as a string without leading zeros ("0" if nothing is left). For ("1432219", 3) the answer is "1219".
Write remove_k_digits(num, k) with an increasing stack: for each digit, while k > 0 and the top is larger than the digit, pop; then push. If k is still positive at the end, drop digits from the end. Strip leading zeros.
Argue the step directly in a comment: two candidates of the same length first differ at some position, and the one with the larger digit there is larger, no matter what follows. So when the top is larger than the next digit: with the digits below it fixed, any candidate that keeps the top has it at that position, while dropping it (and keeping the next digit) puts a smaller digit there, so deleting the top wins whatever follows. Greedy proofs in general are DSA Topic 20, named only.
Write remove_k_digits_brute(num, k) over itertools.combinations of kept positions (length at most 10), compare by numeric value, and fuzz including the edge cases: leading zeros, k >= len, k = 0, and an already increasing number. Print those edge cases.
Choose heights h[i] <= cap[i] so that the heights rise (never decrease) to one peak and then fall (never increase), with the largest possible sum. Return that sum (0 for an empty list). For cap = [5, 3, 4, 1, 1] the best is h = [5, 3, 3, 1, 1] (a peak at the first item), sum 13.
best_mountain_brute(cap): for each peaki, seth[i] = cap[i]and walk left and right with a running minimum. Count the steps.left_profile(cap):best[i]is the largest sum ofh[0..i]that is non-decreasing withh[i] = cap[i]. Ifjis the previous index withcap[j] <= cap[i](found by a monotonic stack), then positionsj + 1..iall getcap[i], and everything up tojisbest[j]:best[i] = cap[i] * (i - j) + best[j](withbest[-1] = 0). Return(best, pushes, pops).best_mountain(cap): the right side is the left profile of the reversed list. The peak atigivesleft[i] + right[i] - cap[i].- fuzz on few-distinct and random caps from size 0, then count the work at
n = 1,500.
People of distinct heights stand in a row, facing right along it. Person i can see person j > i when everyone standing between them is shorter than both of them. For each person, count how many people to their right they can see. For heights [10, 6, 8, 5, 11, 9] the answer is [3, 1, 2, 1, 1, 0].
can_see_truthchecks every pair with a running maximum of the people in between:O(n^2).can_seescans from the right with a decreasing stack of indices. Each shorter person popped is seen, and the first taller person left on the stack is seen too. Argue why a popped person is never needed by anyone further left.- Count pops, assert
pops <= pushes == n, and compare the counted work on increasing, decreasing and random heights. Fuzz on seeded permutations, starting at size 0.
A ramp is a pair i < j with a[i] <= a[j], and its width is j - i. Find the widest ramp (0 if there is none).
Only a prefix minimum can start the widest ramp: if some earlier item is smaller or equal, it makes a ramp at least as wide. So:
ramp_truth: all pairs,O(n^2).ramp_sort: sort the indices by value (DSA Topic 9,O(n log n)) and keep the smallest index seen so far.ramp_bisect: keep the prefix minimums as a decreasing stack, then binary search it for eachj(DSA Topic 3).ramp_stack: build the same decreasing stack of prefix minimums, then scanjfrom the right and pop whilea[top] <= a[j]:O(n).
Fuzz all four, then count the steps of each at n = 20,000 and print the times beside the counts, with no verdict from the clock.
Find the shortest contiguous stretch of a list that, once sorted, sorts the whole list, and return its length (0 if the list is already non-decreasing). [1, 3, 5, 4, 2, 6, 7] gives 4 (the stretch 3, 5, 4, 2, indices 1 to 4).
DSA Topic 4 solved this with two scans and checked it by sorting. stretch_scans and stretch_sort below are exactly that two-scan answer and that sort check, restated as baselines. The new content is stretch_stacks.
Write three ways:
stretch_sort: sort a copy and compare it with the original (DSA Topic 9,O(n log n)), the Topic 4 check.stretch_stacks(the new method): a monotonic stack from the left finds the leftmost index that has a smaller item somewhere after it; a stack from the right finds the rightmost index that has a larger item before it.O(n)time,O(n)space.stretch_scans: the Topic 4 answer, two scans with a running maximum and a running minimum,O(n)time andO(1)extra space.
Fuzz all three against a brute force that tries every window (small lists, with few-distinct values). Then at n = 100,000 print counted steps and times for a random list and for a nearly sorted one, and print the time ratios. Close with a line driven by the random-list ratios: name the fastest method only if it wins by 2x or more, and say whether the C sort, despite more counted steps, is slower than the stacks.
The min-product of a subarray is its minimum times its sum. Given a list of positive integers, find the largest min-product over all non-empty subarrays (0 for an empty list). For [3, 1, 5, 6, 4, 2] the answer is 60, from [5, 6, 4] (minimum 4, sum 15).
With item i as the minimum, the best subarray stretches to just inside the nearest strictly smaller item on each side. Find those two boundaries with two monotonic passes, and get each sum in O(1) from prefix sums (DSA Topic 6).
max_min_product_brute: for each start, extend with a running minimum and sum, counting steps:O(n^2).prev_smallerandnext_smaller: indices of the nearest strictly smaller item (-1 andnmean none). Count pushes and pops and assertpops <= pushes == nin each.max_min_product: combine them with the prefix sums.- Fuzz on empty, one item, all equal, increasing, decreasing, few-distinct values and random lists.
Design a FreqStack with push(x) and pop(). pop removes and returns the most frequent value in the stack, and among values tied on frequency, the one pushed most recently. After pushing 5, 7, 5, 7, 4, 5, four pops return 5, 7, 5, 4. Popping an empty stack raises IndexError.
NaiveFreqStackkeeps one list and scans on every pop, counting the items it examines.FreqStackkeeps aCounterof frequencies, a dict from each frequency to a stack of values, and the highest frequency.pushappends to the stack for the value's new frequency.poptakes from the highest frequency and lowers it when that stack empties. Both operations are amortisedO(1).- Fuzz both with seeded random operations, including popping when empty.
A heap would also do the job (DSA Topic 15), named only.
You may only use push, pop, peek and is_empty on stacks, and you may have one extra stack. Sort a stack so that the smallest item is at the bottom and the largest on top.
The method: pop an item from the source, move every larger item from the result stack back across to the source until the item's place appears, then push it. Wrap the stack in a class that exposes only those four operations and counts them, so the fuzz proves nothing else was used.
- Count the moves (items moved back across) when the pops arrive in ascending order, in descending order and in random order, at
n = 1,000. Assert that the moves equal the number of inversions in the pop order, and compare with the shifts insertion sort (DSA Topic 9) makes on the same pop order. - Show how many comparisons
sorted()needs once the constraint is lifted. - Fuzz against
sorted, starting at size 0.
In each round, every item that is smaller than its left neighbour is removed, all at the same moment (neighbours are taken from the list as it stood at the start of the round). Count the rounds until a round removes nothing. For [5, 3, 4, 4, 7, 3, 6, 11, 8, 5, 11] the answer is 3, and for [4, 5, 7, 7, 13] it is 0.
rounds_simulateplays the rounds and counts the items it looks at. Build an input where it doesO(n^2)work.rounds_stackkeeps a stack of(value, rounds_until_removed). A new item pops the earlier items that are<=it and takes the slowest of their rounds plus one, or 0 if nothing larger is left beneath it. The answer is the largest value ofrounds_until_removed. State the amortised cost and the worst single step.- Fuzz against the simulation, including empty, one item, all equal and few-distinct lists, and compare counted work at
n = 2,000.
This question previews DSA Topic 12 with one small node class: _Node with value and below. In a linked stack, push can return a new top that points at the old top without changing it, so every earlier version of the stack still exists and shares all the nodes beneath it. (new.below = old is a pointer assignment; in C you would also have to decide who frees a shared node.)
- Write
push(top, value),pop(top)(returns(value, new_top), raisingIndexErroron the empty versionNone) andto_list(top). - Build
nversions this way, and build the samenversions as list copies (versions[k] = versions[k - 1] + [k]). Measure both withtracemallocatn = 1,000andn = 4,000and print the bytes, the node and slot counts, and how the ratio changes. - Use the versions as free undo snapshots: an editor whose text is a stack of characters, where undo returns to an earlier top and typing after an undo starts a branch that leaves the old versions intact.
- Fuzz: random pushes and pops applied to random existing versions, checked against list copies.
DSA Topic 8 wrote a recursive-descent parser and showed how to turn a recursion into an explicit stack, so this question only sets the two side by side. Take expressions of non-negative integers with +, * and brackets, and write:
parse_recursive: a compact recursive-descent evaluator (expression, term and factor functions).parse_stacks: the two-stack one-pass evaluator from earlier in this topic, restated (a value stack and an operator stack, one pop rule for precedence).
The new point is the depth. DSA Topic 8 already showed a RecursionError on deeply nested brackets, and the expression engine in Topic 8's capstone admitted that its recursive parser could not read a 10,000-deep expression. Here the stack evaluator reads that 10,000-deep text directly.
Check both against eval on 10,000 generated shallow expressions (the only use of eval: generated text, ints only). Then feed both a string nested 10,000 brackets deep: catch the failure and print type(e).__name__, never a depth. Time both on the 10,000 shallow expressions and print the ratio.
A stack is needed when more than its top will be read again. When only the top is ever read, a counter or a running maximum does the same job in O(1) extra space. For each of three problems, write a stack version and a constant-space version, and fuzz them against each other:
- Ocean view.
heights[i]is a building; a building has an ocean view (to the right) when it is strictly taller than every building to its right. Return the indices in increasing order. Constant-space idea: a running maximum from the right. - Balancing one kind of bracket. The fewest insertions of
(or)that make a string of only those two characters balanced. Constant-space idea: two counters. - Car fleets. Cars at distinct positions drive to a target at given speeds and cannot pass. A car that catches up joins the fleet ahead and goes at its speed. Count the fleets. Sort by position (DSA Topic 9), then keep arrival times as
Fractions (exact division). Constant-space idea: a running maximum of arrival times.
Print the peak number of items each stack held against the constant-space variable. Then show the contrast: validating whether a pop order is possible for pushes of 1..n reads below the top, and a counter-only attempt fails. Enumerate all permutations for n = 6, print the first one the attempt gets wrong and assert it differs from the real validator.
With one kind of bracket a depth counter is all you need. Q9 already showed that a single depth counter shared by all of ()[]{} accepts ([)]. The natural repair is to give each kind its own counter. Does that close the gap?
three_counters_ok(s): one counter per kind. Openers add 1 to their kind's counter, closers subtract 1; each counter must never go below 0 and must end at 0.one_counter_ok(s): Q9's single shared counter, kept as the baseline row.
Write both, plus stack_ok(s) (the stack checker) and balanced_truth(s) (the pair-deletion oracle). Then run all three checkers on every string over ()[]{} of length 0 to 6. For each checker print how many strings it wrongly accepts, how many it wrongly rejects, and the shortest string it wrongly accepts. Finish with ([)], (] and {[}] run through all three. Explain in a comment why a counter is enough for one kind of bracket and not for three.
stack.pop() and stack[-1] on an empty list raise IndexError. Three programs make that mistake:
check_unguarded(s): a bracket checker that pops on every closer.postfix_unguarded(tokens): a postfix evaluator over+,*and digits that pops two operands for every operator and returnsvals[-1].editor_unguarded(script): an editor whose"undo"step pops the undo stack.
Write smallest_crash(fn, alphabet, max_len, join, min_len=0). It tries inputs in order of length, starting at min_len, and returns the first one that raises, with type(e).__name__. Print the smallest crash for each program. For the postfix evaluator, search over 1, 2, + and *, and also search with min_len=1 for the smallest non-empty crash.
Then write the guarded versions: check(s), which returns the topic's result shape (("unexpected", i, ch) for a closer with nothing open); postfix(tokens), which returns ("too few operands", i, tok) or ("operands left", count); and editor(script), which returns ("nothing to undo", i). Each one tests for empty before it pops.
Show a fourth bug, check_after_pop(s), which pops first and only then asks if not stack. Print its smallest crash, and the wrong answer it gives on "()". Finally, run the three guarded versions on every input up to length 6 (brackets) or 5 (tokens and steps) and show that none of them raises.
A checker can finish its loop with openers still on the stack. Two bugs live there:
is_balanced_bug(s)returnsTrueonce the loop ends, so"((("passes.check_bottom_bug(s)returns the topic's result shape, but for leftover openers it reportsstack[0], the outermost opener. The topic reports the top: the innermost opener, the one that should have closed first.
Write both bugs and their fixes, is_balanced(s) (ending in return not stack) and check(s) (reporting stack[-1]). Write check_truth(s), a brute force that runs pair deletion on (char, index) pairs prefix by prefix, so it returns the same result shape. Check every ()[]{} string up to length 6: assert that the fixed versions always agree with the truth, and print how many strings each bug gets wrong and the shortest one. Then print each bug's output beside the truth on a few leftover-opener inputs, with one caret under the position the bug reports and one under the true position.
The comparison in a monotonic stack's pop condition decides what an equal value means. For a "next" answer, while stack and a[stack[-1]] < x pops only strictly smaller items, so each popped index gets its next strictly greater item. With <= it pops equal items too, and gets the next greater-or-equal item instead. For a "prev" answer the comparison flips, because the answer is whatever survives on top.
- Write
nearest(a, side, want, strict).sideis"next"or"prev",wantis"greater"or"smaller", andstrictchooses between strictly greater (or smaller) and greater-or-equal (or smaller-or-equal). It returns indices, with -1 for none. Keep all eight pop conditions in one table, with the tie rule written beside each. Count pushes and pops, and assertpops <= pushes == n. - Check all eight scans against
nearest_truth(the O(n^2) scan) on every list of values 0..2 of length 0 to 6. Then print one table: for each of the eight, the pop condition and its answer on[2, 1, 2, 2, 0, 2]. - Three problems, each with one correct tie rule.
daily_temperatures(t): for each day, the number of days until a strictly warmer day, 0 if none.stock_span(p): the number of consecutive days ending today with price<=today's.final_prices(p): each price minus the first later price that is smaller or equal (the discount), unchanged if none. Fuzz each one against its O(n^2) truth. Then swap its comparison, find the smallest failing input by exhaustive search, and print the wrong output beside the truth. - Finally, show that on lists with no repeated value, strict and non-strict give identical answers. Say in a comment what that means for a fuzz.
The contribution formula for the sum of subarray minimums gives index i every subarray [l, r] with left[i] < l <= i <= r < right[i]. Sum Of Subarray Minimums used one strict side and one non-strict side. This question shows why the rule has to be mixed, by counting how many indices claim each subarray.
Write bounds(a, left_strict, right_strict), which finds both bounds with two stack scans. A strict side stops at a strictly smaller value; a non-strict side also stops at an equal one. Also write sum_mins(a, left_strict, right_strict), sum_mins_truth(a) (O(n^2) with a running minimum) and claims(a, left_strict, right_strict), which maps every subarray to the number of indices that claim it.
- For strict on both sides and non-strict on both sides, search every list of values 0..2 up to length 6 for the smallest failing input. Print the wrong sum beside the truth, and name each miscounted subarray with its claim count.
- On
[1, 2, 1, 3, 1], print all four rules: the sum, and how many subarrays are claimed 0, 1, 2 and 3 times. - Check that both mixed rules match the truth everywhere and claim every subarray exactly once. Say in a comment which copy of a tied minimum each mixed rule picks.
Here are two bugs in the one-pass largest rectangle, largest_rect(h), which pops on >= and uses a sentinel bar of height 0 at index n:
no_sentinel(h)loops over the real bars only. Bars still on the stack at the end are never measured.short_width(h)keeps the sentinel but measures a popped bar with widthi - topinstead ofi - stack[-1] - 1(oriwhen the stack is empty).
Write the fixed version, both bugs, and largest_rect_truth(h) (O(n^2) with a running minimum). Search every histogram of heights 0..3 up to length 6. For each bug, print the smallest failing input, its wrong answer beside the truth, and how many histograms it gets wrong. Every version counts pushes and pops and asserts pops <= pushes == n; the fixed one also asserts pops == pushes. Show no_sentinel on an increasing histogram, with pushes - pops as the number of bars it never measured, and short_width on [2, 1, 2] and [3, 1, 3, 2, 2]. Explain in a comment what stack[-1] records that top does not. Finally, check the fixed version on every histogram.
In the memory-saving min-stack, the minimums stack gets a push when x <= its top, and a pop when the popped value equals its top. A Min-Stack That Saves Memory pushed on <=; here a search finds what < breaks.
Write MinStack (with <=), StrictMinStack (the < bug) and PairStack ((value, min) pairs). Write run(cls, ops), which replays ("push", x), ("pop", None) and ("get_min", None) steps against a model (a plain list and min()), and returns the first disagreement or crash. Write legal(ops), which only allows pop and get_min on a non-empty stack.
- Run a seeded model-based fuzz until the strict version fails.
- Shrink the failing sequence by deleting one operation at a time, as long as it stays legal and still fails. Print the result.
- Search every legal sequence over pushes of 0..2,
popandget_minup to length 6, shortest first. Print the shortest crash and the shortest wrong value, and assert that the shrunk sequence is as short as the shortest crash. Check thatMinStackandPairStacknever fail on these sequences.
Explain in a comment why the pairs version cannot have this bug, even if its push uses <.
Shunting-yard pops the operator on top before pushing op when PREC[top] > PREC[op] or (PREC[top] == PREC[op] and op not in RIGHT). There are two tempting ways to get that rule wrong:
- higher only,
PREC[top] > PREC[op], never pops on equal precedence, so left-associative operators group to the right:8 - 3 - 2gives 7. - equal always,
PREC[top] >= PREC[op], also pops on equal precedence for^, so2 ^ 3 ^ 2gives 64. (Right-Associative Power met this rule as the left-associative^.)
Write tokenize(text) (a character loop), to_postfix(text, rule) with the three rules in one table, and eval_postfix(post) (exact, with Fraction). Print the postfix and the value under each rule for 8 - 3 - 2, 2 ^ 3 ^ 2 and 16 / 4 / 2. Then generate 3,000 expressions with the fewest brackets (exponents kept to 0..3), and fuzz each rule against eval, counting a matching ZeroDivisionError as agreement. For each wrong rule, print how many expressions it gets wrong and the shortest one, with its postfix under that rule beside the correct postfix.
A - is unary when no operand can stand on its left: at the start, after an operator, after another unary minus, or after ( (and after a comma, in a grammar with function calls). If every - is read as binary, -3 + 2, 2 * -3, -(1 + 2) and 1 - -1 all break.
Unary minus is its own operator, "neg". Its precedence is 3, between * (2) and ^ (4). That is Python's rule: -3 ^ 2 is -(3 ^ 2) = -9, and 2 ^ -1 is 1/2. Being a prefix operator, it is pushed without popping anything. In postfix it takes one operand. ^ is right-associative: 2 ^ 3 ^ 2 is 2 ^ 9 = 512, so ^ goes in RIGHT, and an incoming ^ does not pop an equal-precedence ^ already on the stack.
- Write
tokenize(text, unary=True), producing(kind, text, pos)tuples, where a-becomes("neg", "neg", pos)when the previous token allows it. Withunary=False, every-is binary. - Write
to_postfix(tokens)with the topic's pop rule, pluseval_postfix(post)(exact, withFraction) andcalc(text, unary=True). - Print a table for
-3 + 2,2 * -3,-(1 + 2),1 - -1,-3 ^ 2,2 ^ -1and2 ^ 3 ^ 2: the all-binary result (a value or an error name), the unary-aware result, andeval. The last row has no minus, so both versions give 512. Then print the postfix of-3 ^ 2and2 ^ -1. - Generate 3,000 expressions with unary minus wherever it is legal, with the fewest brackets and exponents in -3..3, and fuzz both versions against
eval. A matchingZeroDivisionErrorcounts as agreement.
Many postfix exercises, like C and Java, say that / on integers truncates toward zero. Python's // floors, so -7 // 2 is -4 where truncation gives -3. The usual patch, int(a / b), goes through a float, and a float has only 53 bits of mantissa.
- Write
div_floor,div_float(int(a / b)),div_trunc(integers only: divide the absolute values, then restore the sign) anddiv_truth(math.trunc(Fraction(a, b))). - Write
eval_postfix(tokens, div)over+ - * /and non-negative literals (write a negative number as0 7 -). Run4 13 5 / +,0 7 - 2 /and10 6 9 3 + 0 11 - * / * 17 + 5 +with//and with truncation, and print where they differ. - Measure: search seeded pairs with
ain[2^53, 2^62]for the first one whereint(a / b)is wrong, and print it with the error. Count the misses on 5,000 pairs below2^40and on 5,000 pairs above2^53, and explain the difference in a comment. - Fuzz
div_truncagainstdiv_truthover every sign pair and sizes up to 40 digits, and show that both raiseZeroDivisionErroron a zero divisor. Add a comment on what Python's unbounded ints hide here (Rule 7).
DSA Topics 2 and 6 showed that out = out + [x] copies the list on every step; here the same copy hides in a stack's push and pop, and the slice pop and the string prepend are the new parts.
Four lines that look like stack code and all work, but the last three build a new list (or string) on every operation:
stack.append(x) # push
stack = stack + [x] # push, written with +
top, stack = stack[-1], stack[:-1] # pop, written with a slice
text = ch + text # build a string back to frontrun_append(n)pushesnitems and pops them all withappendandpop.run_concat(n)does the same with the+push and the slice pop.run_concat_counted(n)repeats it and counts the items copied (the old items on a push, the survivors on a pop). Assert the count is exactlyn * (n - 1).- Time both at
n = 3,000,6,000and12,000withbest_of(min of 3). Print the copy count, the time and the ratio to the previous row for each. Doublingnshould multiply the copies by 4: the counted work carries the claim, and the printed time ratios are shown, not trusted. prepend_text(chars)builds a string withtext = ch + textand counts the characters copied;reversed_join(chars)does the same job with a stack (list,pop, one"".join). Time both at10,000,20,000and40,000characters.- Say which one ships, and give a clock verdict only where the ratio is far from 1.
A document is a list of rows, and each row is a list of numbers, such as [[1], [2]]. An editor pushes a snapshot of the document onto an undo stack before every edit, and undo() pops the stack and makes that snapshot the document. Three ways to take the snapshot:
"live": push the document itself (history.append(state))."shallow": pushlist(state), a copy of the outer list only."deep": pushcopy.deepcopy(state).
Edits are ("add", 0, v) (append v to row 0, an edit inside a row) and ("row", [v]) (append a new row).
- Write
Editor(mode, rows)withdo(op)andundo(). Compare it with a model that keeps a list of every document reached (a deep copy each) and moves back one on undo. - By exhaustive search over short sequences of
A(add),R(row) andU(undo), find the shortest sequence for whichliveandshallowdisagree with the model. Print each one with the state after it and the expected state, and assert that they differ. Show why:liveholds the same object at every history entry, andshallowshares the inner row lists with the document. - Write
CommandEditor, which pushes the inverse of each edit instead of a snapshot (no copies at all). - Fuzz all four editors against the model on 2,000 seeded sequences (length 0 included) and print the failure counts. Python Topic 15 showed alias vs
copy.copyvscopy.deepcopyon one object, and the Commands Or Snapshots question earlier in this topic compared the two undo styles by memory. This one shows what a wrong snapshot restores in an undo stack.
An editor keeps two stacks: undo holds earlier texts and redo holds texts that were undone. do(ch) types a letter; undo() and redo() move a text between the stacks. A new edit must clear the redo stack, because the undone future no longer follows from the present. A buggy editor forgets.
- Write
Editor(clear_redo): withclear_redo=Falseit is the buggy editor. - Write a
Model: a list of every text reached and an index into it. Undo moves the index back, redo moves it forward, and a new edit truncates the list after the index and appends. - By exhaustive search over sequences of
a,b,undoandredoup to length 5, find the shortest sequence on which the buggy editor and the model disagree. Print the sequence, the buggy text and the model's text, and explain why the buggy text is a state that no sequence of edits could have reached from where the user stood. - Fuzz both editors against the model on 3,000 seeded sequences, length 0 included, and print the failure counts.
A monotonic stack that holds values works on distinct data and breaks on duplicates, and it also cannot give a distance. Two bugs. Item 1 comes from a search for the smallest failing input (lists over 0..2, up to length 5). Item 2 is measured over all lists over 0..3 up to length 6.
days_values_buggy(a): daily temperatures (days until a strictly higher one,0if none) with a stack of values, recovering the day witha.index(v). Fix:days(a), with indices.circular_both_passes(a): the circular next greater value, scanning2npositions and pushing the index on both passes. Measure whether this gives wrong answers or only extra pushes over all inputs up to length 6 over0..3, and print which. Fix:circular(a), which pushes only on the first pass.
(The value-keyed dict breaking on repeats was shown in Next Greater For Query Values, so it is not repeated here.) Check every function against an O(n^2) truth. Count pushes and pops in the stack versions.
A test suite for monotonic-stack code should be written once and aimed at any nearest-item function. Work through four steps.
- Inputs. Write
suite_inputs(): seeded adversarial inputs: empty, one item, all equal, increasing, decreasing, zigzag, values0..2, and random wide values. - Suite. Write
run_suite(fn, truth=next_greater_truth)for functions with the contractfn(a) -> (res, pushes, pops), whereres[i]is the index of the itemtruthnames (by default the next strictly greater item,-1if none). It makes three checks on every input and counts the failures of each:
- crash: the function raised (exceptions are caught and counted as failures);
- wrong:
resdiffers from theO(n^2)oracletruth(a)(next_greater_truthby default); - work:
pushes + pops <= 2nfails.
- Variants. Run it on
next_greaterand on five broken variants, each named by its bug:le_instead_of_lt(a<=where<is needed),zero_default(the result starts as[0] * ninstead of[-1] * n),values_pushed(values on the stack anda.indexfor the position),tie_pushed_twice(an item that equals the top is pushed twice), andpop_before_check(apop()before the emptiness check). Then aim the same suite at a second direction: a correctprev_smaller(previous strictly smaller item) checked againstprev_smaller_truth, and a copyprev_smaller_gtwith>where<belongs, which the suite must flag. - Table. Print a table of failures per check, assert that the correct functions pass everything and that every broken one is caught by at least one check, and print which checks catch each variant alone (what the suite would miss if that check were removed).
Build lint(src) for source-like text. It checks ()[]{} with a stack, as the topic's bracket checkers do (positions and line:col, 1-based, are the same ideas as before: one line of back-reference, no re-teaching). It adds three things:
- Ignored regions, tracked in the same character loop by a small state machine: brackets inside
'...'and"..."strings (a backslash escapes the next character) and after#to the end of the line are not brackets. A string that reaches the end of its line is an error:unterminated string. - Every error as
line:colwith a message naming the expected closer, returned as(index, line, col, kind, message). - Recovery, so one slip does not hide the rest. A closer that does not match the top: if its partner is an opener deeper in the stack, the openers above it are reported as unclosed and popped, and the closer then matches; if there is no such opener, the closer is reported and skipped. Keep a count of each kind of opener on the stack so that "is there a partner anywhere?" is O(1).
Show it on four snippets with a caret line under each error. Fuzz the brackets-only subset: lint reports nothing exactly when pair deletion says the string is balanced, and deleting every flagged character leaves a balanced string (the recovery property). Time it on 10^5 characters of source, and on the adversarial "(" * 50000 + "]" * 50000.
Build a complete calculator from three pieces the topic taught separately. The expression-parsing questions of Topic 8 were recursive descent; this one is a stack machine end to end.
tokenize(text): a character loop (nore) returning(kind, text, pos)with kindsnum,name,op,lp,rp,comma. A bad character raisesCalcError(message, pos).to_postfix(text, names): shunting-yard with+ - * /(left, precedence 1, 1, 2, 2), unary minus (3), right-associative^(4), brackets, and the functionsmax,min(one or more arguments) andabs(exactly one) with argument counts kept per open bracket. A function name is not pushed by itself. It rides on the(that follows it, and that operator-stack entry also counts commas. A comma pops operators down to that(and adds 1 to its count. The)pops down to the(and removes it. If that entry carries a function name, it emitsname/argcwith argc = commas + 1, after checking the count. Variables come from the dictnames. Python's unary rule:-3 ^ 2is -9, and2 ^ -1is 1/2.evaluate(postfix, names): an operand stack ofFractions (exact division; an integer-valued result prints as an int). Pop the right operand first.calc(text, names)returns(postfix_text, value). Every failure is aCalcErrorwith a position, rendered with a caret line: a bad bracket, a missing operand or operator, an unknown name or function, a wrong argument count, a non-integer exponent, and division by zero at its/.- Fuzz against
eval(used only as an oracle, on generated text, withF(3)for numbers and**for^) on 2,000 generated expressions that use every feature. A division by zero must raise in both.
Put every stack of this topic behind one interface (push, pop, peek, __len__; pop and peek on an empty stack raise EmptyStack) and compare them in one place. The stacks:
ListStack: a class around a Python list.NodeStack: linked nodes with one_Nodeclass (__slots__ = ("value", "below")). This previews DSA Topic 12; the walk is only used to print.FixedStack(capacity): a preallocated array and a top index;StackFullon overflow.TwoInOne: two stacks sharing one array, one growing up from index 0 and one growing down from the end;view(0)andview(1)are two stacks with the interface above.StackFullonly when the whole array is full.MinStackPair(a second stack of running minimums, one entry per item) andMinStackMins(a second stack that stores a minimum only whenx <= top, the minimums-only stack of the min-stack question earlier in this topic). Both also havemin().
The bare Python list (append, pop, [-1]) is the baseline that ships.
- Model-based fuzz: each stack against a plain list on 3,000 seeded operations, starting with a pop on empty. The two-in-one views are fuzzed together, interleaved. Min-stacks also check
min()againstmin(model). - One table: bytes per item (
tracemalloc, 10^5 pushes of pre-built ints), time for 10^5 pushes plus 10^5 pops (min of 3), the time as a multiple of the bare list, and the stated worst-case cost per operation. - Draw every verdict from the printed numbers.
An editor keeps the text on two stacks: left holds the letters before the cursor (top = the letter just before it), and right holds the letters after it in reverse (top = the letter just after it).
TwoStackText:insert,backspace,delete,move(k)(positive = right; stops at the ends; O(1) per letter moved),move_to(pos),cursor()andtext().Editor(TwoStackText):key_type,key_backspace,key_delete,key_move,undoandredo. Undo and redo use commands(kind, pos, letters, cursor before, cursor after). Consecutive typed letters merge into one undo step, until anything else happens (a move, a delete, an undo). A new edit clears redo.match(): the index of the partner of the bracket just after the cursor (()[]{}, other letters ignored), found by walkingright(orleft) without moving the cursor, orNone.- Model-based fuzz: a
Modelon plain strings (text, cursor, and a list of undo steps with before and after states) must agree with the editor on text and cursor after every keystroke.match()is checked against a brute force: the nearestjfor which the bracket letters oftext[i:j + 1](ortext[j:i + 1]) reduce to nothing by pair deletion. - Measure against an editor that rebuilds the string on every keystroke (
text = text[:c] + ch + text[c:]) on 2 * 10^4 seeded keystrokes, at three document sizes. Print the work counted (characters the rebuild copies, letters the stacks move) and the times.
Generate a seeded random walk of 10^5 daily prices (integers, at least 1) and daily volumes. Answer five questions, each with one monotonic stack that counts pushes and pops and asserts pushes + pops <= 2n:
spans_online(prices): today's span, the number of consecutive days up to today whose price is at most today's. Build it on aSpanTrackerwithnext(price)that sees one price at a time.days_until_higher(prices): days until a strictly higher price (0if none).previous_higher(prices): the index of the previous strictly higher price (-1if none).lowest_width(prices): for each day, the length of the longest run of consecutive days containing it in which its price is the lowest (ties allowed). Equal prices must share the same window.largest_volume_rectangle(volumes): the largestdays * minimum volumeover any run of consecutive days, returned as(area, start, end).
Work in four steps. STEP 1: write the five functions above. STEP 2: check each against an O(n^2) oracle (*_truth, counting inner-loop steps) at n = 2,000, and print counted steps and times side by side; fuzz small cases first (size 0, few distinct values). STEP 3: run the five alone on 10^5 days. STEP 4: print a short report of the five most notable findings, each computed from the results.
A profiler records a program as events (t, kind, name), where kind is "enter" or "exit" and t is an instant on the clock. The time from one event to the next belongs to the function on top of the call stack. Build the profiler that replays such a log.
- Write
simulate(rng, steps): a seeded random program that writes a log, using a fixed table of which function may call which. Recursion must happen:exprcallsexpr, andtermcallsexpr, so the same function can be on the stack more than once. - Write
profile(events), which replays the log on a stack of frames and returns("ok", report). The report holds:- the number of calls per function;
- the exclusive time per function, using the same charge-the-top rule as the exclusive-time question earlier in this topic (a one-line reuse, not a new derivation);
- the inclusive time per function, counted once even when the function is already lower on the stack. Show on a small hand-written log that adding up every frame's span counts the inner call twice;
- the maximum depth;
- the folded stacks for a flame graph: one line per call path, such as
main;parse;expr 12, printed in sorted order.
- Reject a malformed log at its first bad event, by its 1-based number, as
("bad", number, reason). Cover a malformed event, an exit with nothing running, an exit for the wrong function, time running backwards, and a function that never exits (report the event that entered the innermost open call). - Check every number in the report against
profile_by_tick, a brute force that rebuilds the whole stack from scratch for every clock tick. Run 300 seeded logs, starting with the empty log. Check the maximum depth with a plain replay instead, because a call that enters and exits at the same instant takes no ticks.
State the time and space of the profiler, including what the folded path strings cost.
Build a tiny bytecode interpreter with two stacks: an operand stack for values, and a frame stack for calls. A frame holds the return address and the locals, and the arguments of a call are its first locals.
Instructions: PUSH c, LOAD i, STORE i, ADD, SUB, MUL, LT (pushes 1 or 0), JZ label (pops a value and jumps if it is 0), JMP label, CALL label n (moves the top n values into the new frame's locals), RET (pops the frame and leaves the return value on the operand stack), PRINT and HALT.
- Write
assemble(text), which turns lines likefact: LOAD 0 ; commentinto instruction tuples and resolves each label to an address. - Write
run(code, max_frames, trace=False), returning the printed values, the number of instructions executed, the peak operand depth and the peak frame depth. - Write a recursive factorial and an iterative sum
1 + ... + nin this assembly. Print a trace offact(2), check both programs againstmath.factorialandn(n+1)/2for n = 0..30, and print the counts for n = 10, 100 and 1,000. Say what grows with n in each program and what stays flat. - Run
fact(5000)on the machine, and compare it with a recursive Pythonfactat the same depth. Explain the difference: the machine's frames are list items. Then setmax_frames = 100and show the machine's own "stack overflow" error.
CPython also runs bytecode on a stack machine. Name the dis module, but do not import it.
Write a small template engine with three kinds of tag: {{ name }}, {% for x in items %} ... {% endfor %}, and {% if name %} ... {% endif %}.
tokenize(text): a character loop (nore) that makes("text", s, pos),("var", name, pos)and("tag", words, pos)tokens. A{{or{%that is never closed is an error.check(text, tokens): a stack that checks the blocks nest, and reports the first error asline:colwith a caret line under it. Cover a block closed by the wrong end tag (name where the open block started), an end tag with nothing open, a block that is never closed (report the innermost one), and an unknown tag. While it checks, it records where each block ends, so the renderer can jump there.render(text, data, max_out): run the tokens with a stack of scopes. The data dict is at the bottom, and each openforpushes one dict. A name is looked up from the innermost scope outward, so an innerxhides an outerx. Show this with{% for x in x %}, where the items are read before the new scope is pushed. An unknown name is an error with its position. Raise an error once the output passesmax_outcharacters.- Render a report template on 500 seeded data sets, starting with empty lists, and compare each result with the same text built directly by Python loops.
State the time and space of each function.
Chemical formulas look like K4[ON(SO3)2]2. An element is an uppercase letter followed by optional lowercase letters. A group uses any of (), [] and {}. A number multiplies the element or group just before it.
weigh(s): a stack of Counters, one for each open group. A closing bracket pops the group's Counter, multiplies it by the count that follows, and adds it into the Counter below. Return("ok", Counter)or("error", pos, reason)for: a bracket that closes the wrong kind or closes nothing, a group never closed (the innermost one), an unknown element, a count of 0 or a count with a leading zero, an empty group, and any other character.- Print five formulas in sorted element order with their molar mass, using a small mass table and rounding to 3 decimals. Print each error with a caret under its position.
weigh_brute(s): a brute force that expands the innermost group as text, again and again ((SO3)2becomesSO3SO3), and then counts the flat formula. It must reject exactly the stringsweighrejects. Watch out for expansion gluing a stray lowercase letter or digit onto a neighbour, which would turn an invalid string into a valid one.- Fuzz
weighagainst the brute force on generated valid formulas and on random strings over a small alphabet, starting with the empty string.
State the time and space of both, including how far the brute force's text can grow.
Cars numbered 1..n arrive in that order on a track. Beside the track is one dead-end siding, which works as a stack. Each car goes IN to the siding and later comes OUT onto the exit track. Which orders can leave on the exit track?
- Write
produce(target). It brings cars in until the wanted car has arrived, then sends it out if it is on top of the siding. Return the moves (IN 3,OUT 3, ...), or the wanted car and the siding when the run gets stuck. Print one order that works and one that does not. Checking whether a pop order is valid was done earlier in this topic, so cite it in one line. Here the moves themselves are the output. - The claim to test: "an order can be produced iff it has no i < j < k with
target[k] < target[i] < target[j](no 231 pattern)". Check this claim, and the alternative "no 312 pattern" (target[j] < target[k] < target[i]), against the simulation on every permutation for n = 0..8. Count the orders that can be produced, and compare the counts with the Catalan numbers. Print the smallest counterexample to the claim that fails, and prove the one that holds, in both directions. - The reverse job: cars arrive in some order and must leave as
1..n. Check that the 231 pattern describes this job instead, again on every permutation up to n = 8. Then explain why the two jobs are inverses of each other.
An interviewer asks: "Tell me about stacks." Give a spoken-style answer in six points. Back every point with a few printed lines from running code, not with claims alone.
- Last in, first out, and why the top goes at the end of a Python list. Count the items shifted by pushes and pops at the front and at the end, and print the times beside the counts.
- When a counter is enough, and when the stack must remember which opener is open. Use
([)]. - How shunting-yard decides to pop. Show it on a left-associative chain, on a right-associative
^, and on mixed precedence, printing every pop. - Undo and redo with two stacks, and why a new action clears the redo stack.
- The monotonic invariant. Print the stack after each step of a next-greater scan.
- Why "each index is pushed once and popped once" makes a
whileinside aforO(n). Print the counts, and the worst single step, for n = 10^5.
For each workload below, choose a structure and back the choice with counted work, or with a timing where the clock clearly separates the options.
- A config file of 10^6 characters with three bracket kinds and quoted strings, where a bracket inside quotes is just text.
- The maximum of the last k sensor readings. What does a stack fail to do here?
- Undo in a large document.
- The nearest earlier lower price for each of 10^6 days.
- The number of sessions open right now.
- 10^4 user formulas, each evaluated many times for different values of
x.
Where an earlier question in this topic already measured the trade-off, cite it in one line instead of measuring it again. Name any structure that belongs to a later topic, but do not build it.
For each item, find the index of the second item to its right that is strictly greater. Use -1 if there is none.
- Write the O(n^2) brute force.
- Write the O(n) version with two monotonic stacks. The first stack holds the indices still waiting for one greater item. The items popped from it, which have now found one greater item, move in their original order to the second stack. An item popped from the second stack has found its answer. Argue the O(n) bound, and assert it with counted pushes and pops at n = 10^5.
- Fuzz against the brute force on the edge shapes: empty, one item, all equal, increasing, decreasing, zigzag, few distinct values, and random.
- Follow-up: why must the move keep the original order? Find a failing input by search when the moved items are pushed in pop order, and print it beside the truth. Also show what goes wrong when the second stack is resolved after the move instead of before it.
- Follow-up: the k-th greater element with k stacks, in O(k * n). Check it against a brute force for k = 1..4.
"Count the submatrices of a 0/1 grid that contain only ones." Work through it the way you would in an interview.
- Stage 1: the brute force for small grids, which tests every rectangle.
- Stage 2: heights per row. This is the running count from the largest-rectangle-of-ones question, so cite it in one line. For each bottom-right corner, walk left keeping the minimum height. This is O(rows * cols^2).
- Stage 3: a monotonic stack per row, with
count[j] = count[p] + h[j] * (j - p), where p is the previous index with a strictly smaller height.count[j]is the number of rectangles whose bottom-right corner is in column j. Prove the recurrence, and say which earlier counting idea it is. This is O(rows * cols). - Fuzz each stage against the one before it, starting with grids that have 0 rows or 0 columns. Print the counted work of stages 2 and 3, with times beside the counts.
- Follow-ups: count the all-zeros submatrices; keep memory at O(cols) by streaming the rows from a generator, and measure it with
tracemalloc; and say what to do with a grid too wide to hold even one row (name the column-strip approach, do not build it).
Build a formula sheet over seeded price series. A cell holds a number, a series (a list of numbers), or a formula written as text starting with =.
- Write the four series functions with monotonic stacks:
span(the days in a row, ending today, with a price at most today's),nextup(the days until a strictly higher price, 0 if none),maxrect(the largest rectangle under the series as a histogram), andwater(the water trapped, using the stack version). Each one assertspushes + pops <= 2n, or its own bound with a sentinel. - Tokenise each formula with a character loop. Check its brackets with a stack and report errors as
line:colwith a caret. Then turn it into postfix with shunting-yard. Handle unary minus with Python's rule (-3 ^ 2is -9), right-associative^, and the functionsspan,nextup,maxrect,water,sumandmax, each with a fixed argument count that is checked. Report every syntax error with its position. - Evaluate the postfix on an operand stack. Use
Fractionfor exact division, and work element-wise when an operand is a series (a series with a number, or two series of equal length). - A
Sheetclass. References between cells are evaluated with an explicit stack of frames that resume where they left off, the conversion from DSA Topic 8, so a chain of 10^4 cells works where a recursive evaluator fails. A reference to a cell that is already on that stack is circular. Report it with the chain, such asa -> b -> c -> a. Membership in the stack is the whole check (cells that refer to cells form a graph, and this walk is a depth-first search; both in general are DSA Topic 17, named only). Edits go through undo and redo stacks of commands. - A demo on six workloads: spans, waits and element-wise returns on a price series; formulas with errors; an edit that is undone and redone; a 10^4-cell chain; a circular reference; and the series functions at n = 10^5.
- Fuzz. Check 3,000 generated scalar formulas against
eval, using only the generated strings, with each number written asF(n)and^as**; division by zero must raise in both. Feed random strings in and expect an error, never a crash. Check the four series functions against O(n^2) oracles on the edge shapes, from the empty series up. Check undo and redo against a model: the list of every state reached, with an index into it.
Stuck? Solve it with a mentor.
Your first 1-on-1 session is free.