Skip to content
Tech Interview Prep
Technical interview guide

Stacks

LIFO ordering for tracking nested structure: matching parentheses, undo history, and monotonic sequences.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with container costs and recursion limits cited from CPython 3.14, the C++ standard containers, and java.util as of Java 21.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Walk through balanced-bracket validation, including where engineers most often get it wrong.

Answer

First 90 seconds

Clarify three things before writing code: which delimiters count ((), [], {} or just one) whether the string is bracket-only or also contains other characters, and whether "" is valid (it is). Then answer: keep the openers on a stack; a closer must match the most recently opened delimiter, so pop and compare; when the input ends, the stack must be empty. One pass, O(n) time, O(d) space for maximum nesting depth d.

If brackets are the whole alphabet, counting is still not enough: ")(" has equal counts and no valid structure, and neither does "([)]".

Python
def valid(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False       # closer with nothing open, or wrong type
        else:
            return False           # contract: input is bracket-only
    return not stack               # any opener left is unclosed

Trace of "({[]})"

readstack after
(['(']
{['(', '{']
[['(', '{', '[']
]['(', '{']
}['(']
)[]

Ends empty, so valid. The not stack or ... order is load-bearing: on input ")" the or short-circuits and no pop happens. Written the other way round, stack.pop() != pairs[ch] or not stack raises IndexError on that same input.

Test cases

inputresultreason
""Truenothing opened, nothing left
"({[]})"Trueevery closer matches its opener
")("Falsefirst character is a closer with an empty stack
"([)]"False')' pops '[' and finds a type mismatch
"()]"False']' arrives with an empty stack
"((("Falsestack holds three unclosed openers at the end

Where engineers get it wrong

  1. Counting instead of matching. ")(" and "([)]" each have equal opener and closer counts, so a counter says valid. Detect it with tests that include balanced-count, invalid-structure strings rather than only the happy path.
  2. Dropping the final not stack. "(((" then returns True. One all-openers test catches it.
  3. Popping before checking emptiness, as above. A sentinel opener like "#" instead of the emptiness check avoids the crash but silently accepts the input.
  4. Validating brackets where brackets are data. A ")" inside a JSON string, a regex literal or a C comment is not structure. Hand-rolled validators pass bracket tests and fail language tests: push the job to json.loads, expat or a real lexer and let it own the state machine. Differential fuzzing against that parser finds the gaps.
  5. Unbounded depth as an input vector. 10^7 '(' characters grow the list to 10^7 eight-byte pointers, roughly 80 MB, before the function returns False. Production parsers cap nesting depth for exactly this reason; cap yours at a documented maximum and reject past it.

Alternatives, and when the stack is unnecessary

  • Single delimiter type: an int counter, O(1) space. Reject the moment it goes negative, require zero at the end.
  • Depth bounded by the grammar (say 64): fixed char array plus an index, no allocation, no growth.
  • Recursion: same invariant, implicit stack, one frame per nesting level. CPython's default recursion limit is 1000 (sys.getrecursionlimit()), so a recursive validator raises RecursionError on input the loop handles without noticing, and reporting the index of the offending character means threading state through the call chain.
  • Regex: only for bounded nesting. A regular expression cannot count arbitrary depth, so (([^()]*)) strips one level at a time; repeated reduction to a fixpoint is not validation.

The explicit stack is never the wrong answer for arbitrary nesting with mixed delimiter types. It is just more machinery than one delimiter type or a grammar-bounded depth needs.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-3

Explain the stack contract and how it changes a production decision.

Answer

Core answer (first 90 seconds)

The stack contract is three guarantees: LIFO order, access only at the top, and O(1) push/pop/peek. The production decision it changes is whether the call stack carries your traversal state or an explicit heap-allocated stack does, and whether that stack is bounded.

Concretely: a service that parses untrusted nested input (JSON, an expression, a directory tree) recurses once per level. The call stack is fixed at 8 MB on glibc/x86-64 (ulimit -s), and a typical frame is on the order of 100 bytes, so you get roughly 80,000 levels before overflow. Overflow is SIGSEGV, not an exception you can catch; the process dies. A 500 KB payload of [[[[... is 500,000 levels. So: recursion for trusted, shallow input; an explicit stack with a depth cap for anything a client controls.

Mechanism

LIFO is what makes the top the only reachable element, and top-only access is what lets the structure live on a contiguous array with a single length counter: no per-element links, no rebalancing. That is why push/pop are O(1) and why the invariant "everything below the top is untouched" is cheap to reason about.

The contract also fixes ordering. A stack gives depth-first order; a queue gives breadth-first. If you need the shortest path in an unweighted graph, a stack returns a path, not the shortest: the LIFO order is the bug.

Worked trace

Recursion carries depth implicitly; an explicit stack must carry it in the frame, because only the top is reachable.

Python
def depth_iter(root):
    stack = [(root, 1)]
    best = 0
    while stack:
        node, d = stack.pop()
        best = max(best, d)
        for c in node.children:
            stack.append((c, d + 1))
    return best

Tree: root → A, B; A → A1. Trace: pop (root,1), best=1, push (A,2),(B,2). Pop (B,2), best=2. Pop (A,2), best=2, push (A1,3). Pop (A1,3), best=3. Returns 3, matching the recursive 1 + max(depth(A), depth(B)).

Trade-offs

Recursion: no per-frame heap allocation, better locality, but bounded by the thread stack and uncatchable on overflow. Explicit stack: heap-allocated, growable, boundable, but each frame costs an allocation (a Python 2-tuple is 56 bytes plus list overhead) and pointer-chasing hurts cache. Go sits between: goroutine stacks start at 8 KB and grow to a 1 GB default cap, so deep recursion is safe there and the explicit stack is unnecessary.

Bounded stacks: an undo history capped at 100 entries drops the oldest edit on overflow. Exactly right, because LIFO means the recent edits are the ones you keep. A queue would drop the recent ones.

Failure modes

  • Unbounded recursion on client input → SIGSEGV. Detect by fuzzing with nested payloads and watching for process restarts or core dumps; cap depth and return 400.
  • Stack used where BFS is needed → wrong, non-shortest result. Detect with a known-distance test case.
  • Mid-list indexing (stack.pop(0)) → O(n), shifts every element. Detect in review; it is not a stack operation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Describe the monotonic stack and the evidence you would collect before relying on it.

Answer

The 90-second answer. A monotonic stack is a stack whose contents stay sorted by value, so the top is always the nearest unresolved element. Reach for it when you need, for every index, the nearest later element that is greater (or smaller): next-greater-element, daily temperatures, stock span, largest rectangle in histogram. Each index is pushed once and popped at most once, so the pass is O(n) time and O(n) space.

Mechanism. Store indices, not values, so you can write the answer back into position. Before pushing index i, pop every index whose value the new value dominates: the new element is exactly the answer those indices were waiting for. Then push i. The stack's ordering direction is the whole contract: a decreasing stack (values fall from bottom to top) answers next-greater; an increasing stack answers next-smaller. Derive the pop condition from the direction, not from a memorised example.

Python
def next_greater(a):
    out, stack = [-1] * len(a), []          # stack holds indices, decreasing by value
    for i, v in enumerate(a):
        while stack and a[stack[-1]] < v:
            out[stack.pop()] = v            # v is the answer for everything it dominates
        stack.append(i)
    return out

next_greater([2, 1, 2, 4, 3])   # [4, 2, 4, -1, -1]

Trace on [2, 1, 2, 4, 3]:

ivpopsstack afterout
02—[0][-1,-1,-1,-1,-1]
11—[0,1]unchanged
221 (out[1]=2)[0,2][-1,2,-1,-1,-1]
342,0 (out[2]=4, out[0]=4)[3][4,2,4,-1,-1]
43—[3,4]unchanged

Alternatives, and when not to use it.

  • Brute force O(n²): for n up to a few thousand it is the right first move. Trivially correct, and you differential-test the stack against it.
  • Sparse table / segment tree: when the query is "max over an arbitrary range [l, r]" rather than "nearest greater to the right". The monotonic stack cannot answer that; a sparse table gives O(1) range max after O(n log n) build.
  • Monotonic deque: sliding-window maximum, same amortisation, bounded window.

Failure modes.

  • Duplicates. < versus <= decides whether equal elements resolve each other. With < you get next strictly greater; with <= next greater-or-equal. Both are correct for different problems, and the wrong one passes most tests and fails only on arrays with repeats.
  • Direction flip. An increasing stack silently returns next-smaller where you wanted next-greater: wrong on every input, obvious only on a case where the two differ.
  • Wrong query shape. Using it for arbitrary range max returns a plausible-looking wrong number, because it only ever answers the nearest greater.
  • Space. The stack can hold all n indices; you cannot stream a window larger than memory.

Evidence to collect before relying on it.

  1. Differential test against brute force. Random arrays of length 0, 1, 2, 10, 1000 with values drawn from a small range (to force duplicates), plus all-equal, strictly increasing, strictly decreasing. Assert for every i: out[i] == -1, or out[i] > a[i] and no j between i and the index of out[i] has a[j] > a[i].
  2. Pop-count instrumentation. Count pops and assert the total is ≤ n. On n = 10⁶ random ints the count lands near n, which confirms the amortisation instead of assuming it.
  3. Timing at the real size. The constant factor is the index indirection a[stack[-1]]; measure at your actual n rather than extrapolating from n = 100.
  4. Duplicate semantics pinned. Write down which of < / <= your problem needs, and add a test with repeats that fails under the other.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do sentinel elements simplify edge case handling and loop terminations in monotonic stack algorithms?

Answer

Core answer

A monotonic stack keeps its contents ordered by popping anything that breaks the ordering when a new element arrives. That pop loop has two boundaries where either the stack or the input runs out, and both are normally handled with extra branches. A sentinel is a guard value placed at a boundary so the branch disappears.

The two boundaries:

  1. Left (stack underflow). When the pop loop empties the stack, you need a fallback for the left bound: left = stack[-1] if stack else -1. A left sentinel (a virtual index -1, or a real element smaller than every legal input) guarantees the stack is never empty inside the loop, so the ternary vanishes.
  2. Right (input exhaustion). After the scan, elements still on the stack never met a smaller element to their right, so a second drain loop has to resolve them. A right sentinel smaller than every legal input forces every real element to be popped inside the main loop, so the drain pass disappears.

Complexity is unchanged: each index is pushed once and popped at most once, so O(N) time and O(N) space either way. Sentinels buy branch removal, not asymptotics.

Worked example: largest rectangle in histogram

Python
# Python 3.12
def largest_rectangle(heights: list[int]) -> int:
    h = [0] + heights + [0]   # left sentinel at index 0, right sentinel at the end
    stack = [0]                # indices; h[0] == 0 is the virtual left bound
    best = 0
    for i in range(1, len(h)):
        while h[i] < h[stack[-1]]:
            height = h[stack.pop()]
            width = i - stack[-1] - 1   # stack[-1] always exists: h[0] == 0 <= h[i]
            best = max(best, height * width)
        stack.append(i)
    return best

Trace on [2, 1, 5, 6, 2, 3], so h = [0, 2, 1, 5, 6, 2, 3, 0]:

ih[i]pops (height × width = area)stack afterbest
00—[0]0
12—[0, 1]0
21idx 1: 2 × (2−0−1) = 2[0, 2]2
35—[0, 2, 3]2
46—[0, 2, 3, 4]2
52idx 4: 6 × (5−3−1) = 6; idx 3: 5 × (5−2−1) = 10[0, 2, 5]10
63—[0, 2, 5, 6]10
70idx 6: 3 × (7−5−1) = 3; idx 5: 2 × (7−2−1) = 8; idx 2: 1 × (7−0−1) = 6[0, 7]10

Returns 10 (the 5×2 block). Without sentinels the same input needs an empty-stack check on every width computation and a post-loop drain that pops indices 6, 5, 2 with a synthetic right bound of len(heights).

Trade-offs and failure modes

  • Prepend cost. [0] + heights copies the list, O(N) time and memory. For large inputs, keep the array untouched and push the virtual index -1 with a value of -inf instead, or reserve capacity up front in C++/Java.
  • Sentinel collision. The sentinel must be strictly smaller than every legal input. If heights can be 0, a right sentinel of 0 is not strictly smaller, so a trailing zero-height bar is never popped and the stack is not fully drained: harmless here because its area is 0, but wrong if you rely on the drain to finalize other state. For unbounded integer domains, use std::numeric_limits<T>::lowest() or a virtual index rather than a hardcoded constant.
  • Comparison direction. The sentinel only works with the same comparison the loop uses. A non-decreasing stack (< pops) needs a sentinel strictly below the minimum; a non-increasing stack needs one strictly above the maximum. Mixing them silently truncates pops.
  • Detection. A wrong sentinel shows up as a missing final pop: assert the stack is empty (or holds only the sentinel) after the loop in tests, and fuzz against a brute-force O(N²) reference on small random arrays including zeros and negatives.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How do you implement a stack with push, pop, and min/max operations in O(1) time and space complexity?

Answer

What a strong candidate says first (60–120s): "The stack itself is O(N) for N elements. That's unavoidable. The constraint is O(1) auxiliary space for the min/max bookkeeping, plus O(1) per operation. I keep min and max as two scalars and encode the previous min or max into the value I store, so a pop can restore them without a second stack."

Mechanism

Store one encoded value per element. Let min/max be the current extremes.

  • x < min: store 2*x - min, then set min = x.
  • x > max: store 2*x - max, then set max = x.
  • otherwise: store x unchanged.

The encoding is self-identifying. If x < min, then 2*x - min < x = new_min, so the stored value is strictly below the current min. Symmetrically, a new max stores a value strictly above the current max. Interior values stay inside [min, max]. On pop, read the top: below min → it was the min, restore min = 2*min - top; above max → it was the max, restore max = 2*max - top; otherwise it's the literal value. LIFO order guarantees that when you reach an encoded entry, min/max have already been unwound to the values in force when it was pushed.

Implementation (Python 3.11)

Python
class MinMaxStack:
    def __init__(self):
        self._data = []          # encoded values
        self._min = self._max = None

    def push(self, x):
        if not self._data:
            self._min = self._max = x
            self._data.append(x)
        elif x < self._min:
            self._data.append(2 * x - self._min)
            self._min = x
        elif x > self._max:
            self._data.append(2 * x - self._max)
            self._max = x
        else:
            self._data.append(x)

    def pop(self):
        if not self._data:
            raise IndexError("pop from empty stack")
        e = self._data.pop()
        if e < self._min:
            x, self._min = self._min, 2 * self._min - e
            return x
        if e > self._max:
            x, self._max = self._max, 2 * self._max - e
            return x
        return e

    def top(self):
        if not self._data:
            raise IndexError("top from empty stack")
        e = self._data[-1]
        return self._min if e < self._min else self._max if e > self._max else e

    def get_min(self):
        if not self._data:
            raise IndexError("get_min from empty stack")
        return self._min

    def get_max(self):
        if not self._data:
            raise IndexError("get_max from empty stack")
        return self._max

Trace

op_data (encoded)minmaxreturns
push(5)[5]55
push(3)[5, 1]35
push(7)[5, 1, 9]37
push(2)[5, 1, 9, 1]27
get_min()272
get_max()277
pop()[5, 1, 9]372
pop()[5, 1]357
pop()[5]553
pop()[]555

Trade-offs and failure modes

  • Overflow. 2*x - min overflows fixed-width ints when x and min sit near the type's extremes (e.g. int32_t with x = -2^30, min = 2^30). Python's arbitrary-precision ints are safe; in C++/Java use int64_t/long or check before encoding. This is the one real cost of the O(1)-space trick.
  • Non-numeric elements. The encoding needs arithmetic and a total order. For arbitrary objects, fall back to the pair stack: store (value, min_so_far, max_so_far) per element. That is O(N) auxiliary space, so it does not meet the O(1) constraint; say so explicitly rather than presenting it as the answer.
  • Empty stack. pop/top/get_min/get_max on an empty stack must raise, not return None; a silent sentinel hides caller bugs.
  • Stale scalars. After the final pop, min/max still hold the last element's value. That's harmless because the next push resets them, but any code that reads min/max without checking emptiness will be wrong.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Teach largest rectangle in a histogram to an engineer who has only seen it as a rule of thumb.

Answer

Core answer (first 90 seconds)

For each bar, the tallest rectangle that uses that bar's full height stretches left and right until it meets a strictly shorter bar. So the answer is the max over all bars of height[i] * (rightSmaller[i] - leftSmaller[i] - 1). A monotonic increasing stack finds both boundaries in one pass: stack indices hold increasing heights, and when a new bar is shorter than the top, that top bar's right boundary is the current index and its left boundary is the element now beneath it. Every index is pushed once and popped at most once, so it's O(n) time and O(n) space.

Python
def largest(h):
    stack, best = [], 0
    for i, v in enumerate([*h, 0]):        # trailing 0 drains the stack
        while stack and h[stack[-1]] > v:
            height = h[stack.pop()]
            left = stack[-1] if stack else -1
            best = max(best, height * (i - left - 1))
        stack.append(i)
    return best

The width is i - left - 1, where left is the new stack top after the pop, not the popped index. That single line is what people get wrong.

Trace on [2, 1, 5, 6, 2, 3]

ivactionbest
02push 00
11pop 0: h=2, left=-1, w=1 → 2; push 12
25push 22
36push 32
42pop 3: h=6, left=2, w=1 → 6; pop 2: h=5, left=1, w=2 → 10; push 410
53push 510
60pop 5: h=3, left=4, w=1; pop 4: h=2, left=1, w=4; pop 1: h=1, left=-1, w=610

The 5 at index 2 is the winner: height 5, width 2 (indices 2–3), area 10.

Trade-offs

Brute force, for each bar expand outward until a shorter bar, is O(n²) worst case (sorted input) with O(1) extra space. Two-pass nearest-smaller arrays give O(n) time and O(n) space but need two passes and two arrays; the stack does it in one pass with one array. Divide and conquer (split at the minimum bar, recurse both sides) is O(n log n) average but degrades to O(n²) on sorted input because the split is maximally unbalanced. The stack wins on time and simplicity for the general case.

Equal heights: the comparison must be strict >. With >= you pop an equal bar early and still get the correct maximum area, but you lose the leftmost position of the maximal rectangle. If you only need the area, either works; if you need the index, use >.

When not to reach for it: if the histogram is tiny, or you need the rectangle's coordinates under a streaming constraint, the two-pass array version is easier to reason about. The stack is the right tool when you want one pass and O(n).

Failure modes

  • Width from the popped index instead of the new top: understates every rectangle spanning several popped bars. On [2, 1, 5, 6, 2, 3] you'd get 5 instead of 10.
  • Forgetting the sentinel: without the trailing 0, bars still on the stack at the end never resolve. [1, 2, 3] would return 0 instead of 4.
  • Using >= when you need the leftmost index of the maximal rectangle.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

A teammate proposes a design that hinges on storing indices rather than values. How do you evaluate it?

Answer

What I'd ask before judging the proposal

The design is only evaluable against what the consumer needs. Two questions decide it:

  1. Does anything downstream need the position (a distance, a span, an ordering, an identity) or only the value?
  2. Is the underlying array immutable for the lifetime of the structure?

If (1) is "position", indices aren't a preference, they're required: a value can't reconstruct where it came from. If (1) is "value only", indices are pure overhead and I'd push back. If (2) is "no", indices are a correctness hazard, not a micro-optimization.

Why position can't be recovered from a value

Concrete case: "days until a warmer temperature." Input [73, 74, 75, 71, 69, 72, 76, 73], expected [1, 1, 4, 2, 1, 1, 0, 0]. A decreasing monotonic stack of indices:

i=0 t=73  push 0                          stack [0]
i=1 t=74  pop 0 -> out[0]=1-0=1; push 1   stack [1]
i=2 t=75  pop 1 -> out[1]=2-1=1; push 2   stack [2]
i=3 t=71  push 3                          stack [2,3]
i=4 t=69  push 4                          stack [2,3,4]
i=5 t=72  pop 4 -> out[4]=5-4=1
          pop 3 -> out[3]=5-3=2; push 5   stack [2,5]
i=6 t=76  pop 5 -> out[5]=6-5=1
          pop 2 -> out[2]=6-2=4; push 6   stack [6]
i=7 t=73  push 7                          stack [6,7]
leftover 6,7 -> out stays 0

out = [1,1,4,2,1,1,0,0]. The pop writes i - j, and j is the index. Store values instead and the pop hands you 72, not 5, so the span is unrecoverable in one pass.

The honest alternative

Storing values isn't the only alternative: storing (value, index) pairs is. That's the comparison that matters:

RepresentationMemory per entrySpan computableExtra load
index only4–8 Byesone arr[j] read
value onlysizeof(value)nonone
(value, index) pairsizeof(value) + 4–8 Byesnone

Index-only wins when the value is large (a struct, a string handle) and the array is hot in cache: the extra read is a hit, and you avoid duplicating the value. The pair wins when the array is cold or the value is a cheap scalar and you'd rather not chase a pointer.

Failure modes and how I'd catch them

  • Stale index after mutation. If the array is reordered or compacted while the structure is live, arr[j] reads the wrong element. Detect with a debug assertion arr[j] == expected, or by freezing the array for the pass. This is the one that bites in production, not in tests.
  • Off-by-one in the span. i - j vs i - j - 1 is a silent wrong answer. Catch it with a brute-force O(n²) reference on random inputs under ~50 elements.
  • Index width. int overflows past 2^31 elements; use size_t/int64. Catch with a scale test or a static bound check.

When I'd reject indices

Value-only consumers (running max, dedup, membership) gain nothing from indices and pay the indirection. And if the array mutates mid-pass, indices are a correctness hazard; I'd store values or copy the slice instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do you implement expression evaluation for infix notation with operator precedence using two stacks?

Answer

Core answer (first 90 seconds)

Assume the input is already tokenized into a list of integer literals, binary operators, and parentheses, and that we want a single-pass evaluation with no AST. Dijkstra's two-stack algorithm does exactly that: one stack holds operand values, one holds operators and (, and the operator stack is kept precedence-monotonic. When a new operator O arrives, pop and apply every stacked operator whose precedence is >= O's (for left-associative operators), then push O. On ), drain to the matching (. At end of input, drain the rest. Time is O(n), space O(n) worst case.

Mechanism

Each application pops the operator, then pops b then a from the value stack and computes a op b: operand order matters for - and /. The precedence-monotonic invariant is what makes one pass sufficient: by the time O is pushed, everything that must bind tighter than O has already been folded into a value.

Python
# Python 3.12
def evaluate_infix(tokens: list[str]) -> int:
    values: list[int] = []
    ops: list[str] = []
    prec = {'+': 1, '-': 1, '*': 2, '/': 2}

    def apply_op() -> None:
        op = ops.pop()
        b = values.pop()
        a = values.pop()
        if op == '+':   values.append(a + b)
        elif op == '-': values.append(a - b)
        elif op == '*': values.append(a * b)
        else:           values.append(int(a / b))  # truncate toward zero

    for tok in tokens:
        if tok.isdigit():
            values.append(int(tok))
        elif tok == '(':
            ops.append(tok)
        elif tok == ')':
            while ops[-1] != '(':
                apply_op()
            ops.pop()
        else:
            while ops and ops[-1] != '(' and prec[ops[-1]] >= prec[tok]:
                apply_op()
            ops.append(tok)

    while ops:
        apply_op()
    return values[0]

int(a / b) truncates toward zero but routes through a float, so it is wrong above 2^53. For arbitrary-precision integers use q = abs(a) // abs(b); values.append(q if (a < 0) == (b < 0) else -q).

Trace: 3 + 5 * ( 2 - 8 ) / 4

TokenActionvaluesops
3push[3][]
+push[3][+]
5push[3,5][+]
*prec(+)=1 < 2, push[3,5][+,*]
(push[3,5][+,*,(]
2push[3,5,2][+,*,(]
-top is (, push[3,5,2][+,*,(,-]
8push[3,5,2,8][+,*,(,-]
)apply -: 2-8=-6; pop ([3,5,-6][+,*]
/apply *: 5*-6=-30; push /[3,-30][+,/]
4push[3,-30,4][+,/]
endapply /: -30/4=-7; apply +: 3+-7=-4[-4][]

Alternatives, and when two stacks is the wrong tool

ApproachTime / spacePick it when
Two-stack (above)O(n) / O(n)One-shot evaluation, no variables, no reuse
Shunting-yard to RPN, then evaluateO(n) / O(n), two passesYou need the postfix form anyway (VM bytecode, serialization), or you want parsing and evaluation testable separately
Recursive descent / precedence climbingO(n) / O(depth)You need an AST: re-evaluate with different variable bindings, constant-fold, or support unary operators, calls, ternaries

Two stacks is the wrong tool when the same expression is evaluated many times with different inputs: compile once to RPN or an AST and evaluate the cheap loop repeatedly. It is also the wrong tool for grammars that are not simple precedence grammars, or when you need error recovery with source positions.

Failure modes

  1. Operand inversion. Popping b then a and computing b - a silently breaks - and /. Detect with a test like 10 - 3 - 2 (must be 5, not 9).
  2. Right-associative operators. ^ needs > instead of >= in the drain condition. With >=, 2 ^ 3 ^ 2 gives 64 instead of 512.
  3. Unary minus. The algorithm above has no production for it; -3 + 4 fails. Either rewrite -x as 0 - x during tokenization or track an "expect operand" state.
  4. Malformed input. A ) with no ( on the stack, or apply_op with fewer than two values, means the expression is unbalanced. Check ops and len(values) before popping rather than letting IndexError escape.
  5. Recursion depth. Not a problem here: the two-stack loop is iterative, unlike recursive descent, which raises RecursionError past Python's default 1000-frame limit on deeply nested input.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What would you measure before treating infix to postfix conversion as settled?

Answer

Before I'd call it settled I'd want four numbers: differential mismatches against a reference parser (0 over ≥10k generated expressions), operator-pair coverage (which of the k² adjacent-operator pairs the suite actually exercises), max operator-stack depth versus input nesting depth, and malformed-input detection rate (100%, with a token index in the error). Correctness first, then the two things that decide whether it survives production: depth and error behaviour.

Differential correctness. Generate random parenthesised expressions, run both your converter and a reference, compare. Python's eval is the reference for arithmetic:

Python
import random, operator
OPS = {"+": operator.add, "-": operator.sub, "*": operator.mul}

def eval_postfix(tokens):
    st = []
    for t in tokens:
        if t in OPS:
            b = st.pop(); a = st.pop()
            st.append(OPS[t](a, b))
        else:
            st.append(int(t))
    return st[0]

def gen(d):
    if d == 0 or random.random() < 0.3:
        return str(random.randint(1, 9))
    return f"({gen(d-1)} {random.choice('+-*')} {gen(d-1)})"

for _ in range(10_000):
    e = gen(4)
    assert eval_postfix(to_postfix(tokenize(e))) == eval(e), e

Trace (3 + 4) * 2: tokenize → ['(', '3', '+', '4', ')', '*', '2']; shunting-yard emits ['3', '4', '+', '2', '*']; eval_postfix pushes 3, pushes 4, + pops 4 and 3 → 7, pushes 2, * pops 2 and 7 → 14. eval("(3 + 4) * 2") is 14. Match.

Coverage. With k binary operators there are k² ordered adjacent pairs. For + - * / ^ that's 25; a hand-written suite of ten expressions typically hits eight, and the ones it misses are exactly the equal-precedence pairs where associativity decides. Measure the fraction of the 25 where your output differs from naive left-to-right emission: that set is what actually tests the pop condition.

Depth and throughput. Shunting-yard is O(n) time and O(p + d) stack, where p is the number of precedence levels and d the paren nesting. Measure max stack depth against nesting: a 10,000-deep expression needs ~10,000 frames, which is why a recursive-descent parser dies at Python's default recursion limit of 1000 while the explicit stack survives. Measure time at 10⁴, 10⁵, 10⁶ tokens; each step should be ~10×. A 100× step means a quadratic pop loop.

Malformed input. Mismatched parens, trailing operators, unknown tokens. On a mutation corpus, detection must be 100% and the error must name the token index: silently emitting a wrong postfix string is the failure that reaches production.

Alternatives. Recursive descent or a Pratt parser gives the same O(n) but handles unary minus, function calls and ternary cleanly; you then emit postfix with a post-order walk. Pick shunting-yard when the grammar is fixed binary operators and you want one pass and no recursion; pick Pratt when the grammar will grow. The measurement that decides between them is stack depth at your real nesting depth, not the happy-path expression.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do you implement an iterative tree traversal using an explicit stack, and what are the trade-offs versus recursion in production systems?

Answer

An iterative tree traversal replaces call-stack frames managed by the language runtime with an explicit collection allocated on the heap (such as a dynamic array or deque).

Mechanism: In-Order Iterative Traversal

In recursion, the runtime implicitly tracks the instruction pointer and registers across child calls. To replicate an in-order traversal (Left, Root, Right) iteratively, you drive a loop with a current pointer and an explicit LIFO stack: push the current node and descend left until hitting null, pop to process the node, and advance the current pointer to that node's right child.

Python
# Python 3.14
def inorder_traversal(root):
    result = []
    stack = []
    curr = root

    while curr is not None or stack:
        # Reach the leftmost node of the current subtree
        while curr is not None:
            stack.append(curr)
            curr = curr.left

        # Current must be None at this point; pop the top
        curr = stack.pop()
        result.append(curr.val)

        # We have visited the node and its left subtree. Now turn right.
        curr = curr.right

    return result

Trace on an Unbalanced Tree

For an unbalanced tree [2 -> left: 1, right: 3]:

  1. curr = 2: push 2, curr becomes 1.
  2. curr = 1: push 1, curr becomes None.
  3. Inner loop terminates. Pop 1. Append 1 to result. Set curr = 1.right (None).
  4. curr is None, but stack holds [2]. Pop 2. Append 2 to result. Set curr = 2.right (3).
  5. curr = 3: push 3, curr becomes None.
  6. Pop 3. Append 3 to result. Set curr = 3.right (None).
  7. Stack is empty and curr is None. Loop terminates, returning [1, 2, 3].

Production Trade-Offs

DimensionRecursive TraversalExplicit Heap Stack
Memory LocationThread call stack (fixed OS/runtime limit).Heap space (bounded by total addressable RAM/cgroup).
Limit & Failure ModeCrash via RecursionError (Python default limit 1000) or OS SIGSEGV / StackOverflowError (typically 1–8 MB default stack size).Fails safely via OutOfMemoryError or explicit length check when exceeding memory budget.
Per-Frame OverheadStores return pointers, caller-saved registers, parameter mappings (typically 32–64+ bytes per call frame).Stores only a raw pointer/reference (e.g., 8 bytes per node reference in a 64-bit vector or dynamic list).
MaintainabilityNatural representation of induction; concise 4-line implementations.More state-tracking boilerplate; non-trivial state machine for post-order traversals.

In production pipelines parsing untrusted, deeply nested inputs (such as deep ASTs, DOMs, or skewed unbalanced binary trees with $N \ge 10^5$), recursive implementations risk abrupt thread death from stack overflow. An explicit stack moves memory consumption to the heap, lowers memory per frame by avoiding runtime metadata, and enables defensive termination if stack depth exceeds an explicit service SLA.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does the call stack as a data structure change if the workload grows by two orders of magnitude?

Answer

The structure doesn't change. The depth and the number of live stacks do, and that moves the failure from "recursion bug" to "capacity line item."

A call stack is LIFO with one frame per active call, and a frame is a return address, saved registers, parameters and locals. Two orders of magnitude more work does not alter any of that. What it alters is how many frames are live at once (depth on one stack, and the count of stacks across threads) and those are the two numbers that decide whether you overflow or run out of memory.

A frame is tens to a couple hundred bytes depending on locals and alignment. Take ~100 bytes as a working figure. Depth going from 10^4 to 10^6 frames is 1 MB to 100 MB of stack, against these defaults:

RuntimeDefault stackFrames at ~100 B/frame
Linux main thread (ulimit -s)8 MB~80,000
glibc pthread8 MB~80,000
HotSpot JVM -Xss (64-bit Linux)1 MB~10,000
Node / V8~984 KB~10,000
CPythonsys.getrecursionlimit() = 1000 (a counter, not a byte bound)1,000
Go goroutine8 KB initial, grows to 1 GB maxgrows

So a workload that pushes depth from 10^4 to 10^6 doesn't change the stack; it walks off the end of it. On the JVM you get StackOverflowError around 10k frames. On Linux you get SIGSEGV past the guard page, which surfaces as a crash, not an exception.

The second axis is concurrency. Two orders of magnitude more requests under thread-per-request means two orders of magnitude more live stacks. 200 threads × 1 MB reserved = 200 MB; 20,000 threads × 1 MB = 20 GB, which no host has. The stack didn't change: the thread model did. You cap the pool, and the queue becomes the new failure point: latency climbs while the pool saturates, then requests time out.

Two failure modes worth naming concretely. Stack overflow: detected as StackOverflowError, RangeError: Maximum call stack size exceeded, or SIGSEGV, and it is deterministic for a given depth, so a single deep input reproduces it. Stack memory as resident cost: detected as RSS growing with thread count and container OOM kills under load, not at rest.

In an interview, state the depth bound and the frame budget, then decide. If depth can reach the input size, convert to an explicit stack, but note that this is the same data structure moved to the heap, where it is bounded by RAM rather than by the thread's reserved stack. In Go, deep recursion trades overflow for heap growth and GC pressure instead, because goroutine stacks grow on demand.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

When would you refuse a design because of tail calls?

Answer

Refuse when the design's correctness or its capacity depends on tail-call elimination that the target runtime does not guarantee. Two conditions have to hold together: the recursion depth is unbounded or attacker-controlled, and the runtime is one where "tail position" is a source-level fact with no runtime consequence. If either is missing, the design is fine.

What the guarantee actually is. A tail call is a call in tail position: its result is the caller's result, so the caller's frame is dead and can be reused. Languages that guarantee this (Scheme per R7RS, Lua 5.4, Erlang/Elixir, Haskell, OCaml) run such a function in constant stack. Most mainstream runtimes don't. ES2015 mandates proper tail calls in strict mode, but only JavaScriptCore ships it; V8 and SpiderMonkey don't. HotSpot doesn't, and the JVM's stack-walking (stack traces, the security model) is the usual explanation. CPython doesn't, and its frames sit on the C stack.

RuntimeTCO guaranteedAt depth 10^5
CPython 3.12NoRecursionError at the default 1000-frame limit
HotSpot (Java, Scala, Clojure)NoStackOverflowError; ~10^4 frames on a 1 MB stack
Kotlin tailrec / Scala @tailrecSelf-calls onlymutual recursion still overflows
V8 (Node, Chrome)NoRangeError: Maximum call stack size exceeded
GoNogoroutine stack grows 8 KB → 1 GB default max, then fatal
Lua 5.4, Scheme, Erlang, OCamlYesconstant stack
Python
import sys
sys.getrecursionlimit()      # 1000

def count(n):
    if n == 0:
        return 0
    return count(n - 1)      # tail position; CPython still pushes a frame

count(2000)
# RecursionError: maximum recursion depth exceeded

The same function in Lua returns 0 at any depth, because the call is a proper tail call. Same source shape, opposite outcome, which is why "tail recursion is a loop" is a language-specific claim, not a general one.

The arithmetic that decides it. A frame is roughly 50–150 bytes. A 1 MB HotSpot thread stack therefore holds ~10^4 frames; a 1 GB Go goroutine stack holds ~10^7. If your design's worst-case depth is under a few hundred, none of this matters. If it's a function of input size, it does.

Failure modes worth refusing over.

  • Attacker-controlled depth. A recursive-descent parser or expression evaluator over untrusted input has depth equal to nesting depth. 100k nested brackets is a few hundred KB of request body and a dead worker. Detect it with a fuzz case that nests to 10^5, not with a unit test at depth 5.
  • Input-dependent, so tests pass. The happy path is shallow; the crash needs the ordering or scale a quick check leaves out.
  • Memory, not just depth. A tail-recursive event loop over 10^7 stream events holds 10^7 frames if the frames aren't reused.

When not to refuse. Bounded depth (a balanced tree, a fixed grammar), a runtime that guarantees the optimisation, or a compiler you've verified emits a jump: Clang's [[clang::musttail]] (Clang 13+) makes the guarantee explicit, and disassembly showing jmp instead of call settles it.

The fix is cheap, which is why refusing costs little: rewrite as an explicit loop, use a trampoline, or keep an explicit heap-allocated stack for the parser. Write the assumption down either way: "this relies on TCO" is a design constraint, and if the runtime doesn't provide it, the design is wrong, not the runtime.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you sort a stack using only push, pop, peek and isEmpty, and what does the auxiliary stack hold at each step?

Answer

Assume one auxiliary stack is allowed; no arrays, no recursion, no other containers. The algorithm is insertion sort with the auxiliary stack as the sorted buffer. Invariant: after each insertion, aux is sorted ascending from bottom to top, so its top is the largest element processed so far. To insert a new value temp, move every element greater than temp from aux back to the input stack, then push temp onto aux. When the input is empty, drain aux back to the input; the input is then sorted with the smallest element on top.

python

Python 3.14

def sort_stack(s): aux = [] while s: temp = s.pop() while aux and aux[-1] > temp: s.append(aux.pop()) aux.append(temp) while aux: s.append(aux.pop()) return s

Trace on input [3, 1, 2] (bottom to top, so top is 2):

StepInput (top right)tempaux (top right)Action
0[3, 1, 2]—[]start
1[3, 1]2[2]aux empty, push 2
2[3, 2]1[1]2 > 1, move 2 back, push 1
3[3]2[1, 2]1 > 2 false, push 2
4[]3[1, 2, 3]2 > 3 false, push 3
5[3, 2, 1]—[]drain aux back

Final input top is 1, then 2, then 3. Popping yields 1, 2, 3 ascending.

Complexity: each element can be moved back to the input stack many times. Worst case is reverse-sorted input, where the inner loop scans the whole auxiliary stack for each insertion, giving O(n^2) moves and comparisons. Space is O(n) for the auxiliary stack. Best case is already sorted input with smallest on top: each element is pushed to aux once and drained once, so O(n).

Failure modes: using >= instead of > still terminates but moves equal elements unnecessarily, increasing the constant. Forgetting to drain aux leaves the sorted result in the auxiliary stack, not the input. Assuming O(1) extra space is possible for arbitrary n is wrong; with only the original stack and no recursion, you cannot sort arbitrary values. Recursion is not allowed because it uses the call stack, which is another data structure. A quick way to detect a broken implementation is to trace reverse-sorted input and count moves; a correct one will show quadratic growth, not linear.

Alternatives: two auxiliary stacks can sort by repeatedly finding the minimum and moving it to a result stack, but that is also O(n^2). If extra memory outside the stack constraint were allowed, popping all elements into an array, sorting with a standard O(n log n) algorithm, and pushing back would be faster but violates the stated constraint.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of the two-stack queue?

Answer

The failure to inject is a workload that empties the outbound stack before every dequeue, followed by a burst that forces one large transfer. Those two sequences separate a team that understands the guard from one that memorised "two stacks, amortised O(1)".

Here is the guarded implementation, traced on push A, push B, push C, pop, push D, pop, pop, pop:

Python
class Queue:
    def __init__(self): self.inbox, self.outbox = [], []
    def push(self, v): self.inbox.append(v)
    def pop(self):
        if not self.outbox:                 # guard: transfer only when outbox is empty
            while self.inbox: self.outbox.append(self.inbox.pop())
        return self.outbox.pop()
opinbox afteroutbox aftermovesreturns
push A[A][]0-
push B[A,B][]0-
push C[A,B,C][]0-
pop[][C,B]3A
push D[D][C,B]0-
pop[D][C]0B
pop[D][]0C
pop[][]1D

Four pushes, four moves: each element crosses between the stacks exactly once. That is the whole amortisation argument, and it is checkable by counting moves.

Now drop the guard: pour on every pop:

Python
def pop(self):
    while self.inbox: self.outbox.append(self.inbox.pop())
    return self.outbox.pop()

At the second pop it pours [D] onto [C,B], giving [C,B,D], and returns D where B is due. The alternating push/pop pattern catches the ordering bug in five operations, before any timing matters. This is the failure worth injecting first: it is a correctness failure, not a performance one, and it hides behind any workload that pushes in bulk before draining.

The second injection is a burst: n pushes, then a single pop. Guarded, that one pop moves all n elements: O(n) for that call. At n = 10^6 that is 10^6 appends and pops inside one call, tens of milliseconds in CPython against microseconds for a guarded pop. Amortised O(1) is true across the sequence; the worst case is not O(1). A team that answers "O(1)" flat is wrong about the tail, and the burst is what makes the tail visible.

Trade-offs decide whether the two-stack queue is even the right structure. If you need worst-case O(1) dequeue, use collections.deque (O(1) at both ends, C-implemented) or a ring buffer; the two-stack queue cannot give it. Two stacks win when you need a persistent queue: the two-list structure is the basis of the purely functional queue, where push and pop return new versions and the amortised bound still holds. A deque cannot be made persistent cheaply. So the deciding question is worst-case latency versus persistence, and the two-stack queue is the wrong answer to the first.

Detection: instrument element moves per operation and assert the running total stays within one move per element; measure p99 of pop under a burst-then-drain workload, not under a steady push/pop mix, which never triggers a large transfer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What trade-off does stack versus queue force that a junior answer usually skips?

Answer

The junior answer stops at "stack means depth-first, queue means breadth-first, so only the visit order changes." The trade actually forced is a guarantee against frontier size, and the pop rule is what enforces the guarantee.

FIFO hands BFS an invariant DFS cannot have: nodes leave the queue in non-decreasing hop count, so the distance recorded the first time a node is discovered is final. That is what makes the BFS answer a shortest path in an unweighted graph, and it is what lets BFS stop as soon as the target is discovered. LIFO gives nothing back: the first path DFS reaches the target on is whichever path its push order happened to try. What you buy for dropping the guarantee is memory. On a uniform tree of branching factor b and depth d, the DFS frontier holds at most b*d entries (the current path plus one unexplored sibling per level), while the BFS frontier is dominated by the deepest level and holds up to b^d.

Same function, one flag, six-node graph:

Python
# Python 3.11
from collections import deque

G = {"S": ["B", "A"], "A": ["S", "C"], "B": ["S", "T"],
     "C": ["A", "D"], "D": ["C", "T"], "T": ["B", "D"]}

def hops(G, src, dst, fifo):
    frontier = deque([src])
    seen = {src: 0}
    pop = frontier.popleft if fifo else frontier.pop
    while frontier:
        node = pop()
        if node == dst:
            return seen[node]
        for nxt in G[node]:
            if nxt not in seen:
                seen[nxt] = seen[node] + 1
                frontier.append(nxt)
    return None

hops(G, "S", "T", fifo=True) returns 2. hops(G, "S", "T", fifo=False) returns 4.

Trace, fifo=False: pop S, push B then A, frontier [B, A]. Pop A (hop 1), push C, frontier [B, C]. Pop C (hop 2), push D, frontier [B, D]. Pop D (hop 3), push T, frontier [B, T]. Pop T (hop 4), return 4. B is still sitting in the frontier and was never expanded, so the 2-hop route S -> B -> T is silently missed.

Trace, fifo=True: pop S, push B then A, frontier [B, A]. Pop B (hop 1), push T at hop 2, frontier [A, T]. Pop A (hop 1), push C at hop 2, frontier [T, C]. Pop T (hop 2), return 2.

That failure is order-dependent. Change S's adjacency list to ["A", "B"] and the DFS branch pops B first and also returns 2. Identical code, identical graph, different edge insertion order, different answer, which is why a small test suite passes by luck and a wide graph does not.

pop rulealgorithmguaranteefrontier, uniform tree (b, d)pop cost
LIFODFSany path, no hop optimalityO(b*d)O(1)
FIFOBFSshortest path by hop count, unweightedO(b^d)O(1)
min on gDijkstrashortest path by cost, non-negative weightsO(V) live entriesO(log V)
min on g + hA*same, if h is admissibleO(V)O(log V)

With b = 10 and d = 6, the BFS frontier reaches 10^6 = 1,000,000 entries against 60 for DFS. DFS is not faster: the worst case still visits up to b^d nodes. The saving is frontier memory, and it is paid for with the guarantee.

Failure modes, with detection:

  • A stack where hop-optimality is required (fewest-moves puzzles, unweighted routing). Detect it with a test graph whose adjacency list puts the long branch first and assert the returned hop count equals the BFS distance; the trace above is exactly that case.
  • BFS on a weighted graph. The result is minimal in hops only, so the route returned can be far more expensive than the cost-optimal one. Swap the FIFO deque for a min-heap on path cost and the same loop is Dijkstra.
  • BFS frontier blow-up on a wide graph. At b = 10, d = 6 you are holding a million entries. Cap the depth and move to A* with an admissible heuristic, or iterative deepening, when memory is the binding constraint rather than time.
  • Recursive DFS down a long chain. CPython's default recursion limit is 1000 (sys.getrecursionlimit()), so a 10,000-node chain raises RecursionError; the explicit deque stack above does not.

Pick from the guarantee the caller needs. DFS when any path, connectivity, cycle detection or topological order is enough and the frontier must stay small. BFS when hop distance or level structure is the deliverable and every edge costs the same. A min-heap when edges carry different costs and the answer has to be minimal in weight.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

What would you ask a candidate who recites amortised analysis of stack algorithms but cannot apply it?

Answer

The recital is the symptom: a candidate who repeats "amortised O(1)" but stalls on an unseen loop has the slogan, not the invariant. Do not ask them to define it again. Ask them to apply it to a sequence they have not seen, then to break it, then to say where the bound stops being usable. Three questions, escalating.

1. Count on new code. Hand them this cold, with the specific input, and ask for the total number of pops over the whole run - not a bound for one iteration:

Python
a = [3, 1, 4, 1, 5, 9, 2, 6]
stack = []
for i, x in enumerate(a):
    while stack and a[stack[-1]] < x:
        stack.pop()
    stack.append(i)

Running it: pushes at i=0..7, so 8 pushes. The while body fires twice at i=2 (pops index 1, then 0), twice at i=4 (pops 3, then 2), once at i=5 (pops 4), once at i=7 (pops 6). Six pops for eight iterations. A reciter multiplies the outer loop by the array and says O(n^2); someone holding the invariant says each index is pushed once and popped at most once, so pops <= n on any input, and the nested loop is O(n).

2. Break the invariant. Move the append inside the while loop, or let an element be pushed twice, and ask whether the O(n) argument survives. This is what separates the slogan from the model: the linear bound rests entirely on "pushed once, popped once", and a candidate who memorised the phrase will keep asserting O(n) after that invariant is gone. The honest answer is that the cost now depends on the input, and the worst case is quadratic.

3. Price the constant, then the tail. "List append is amortised O(1) even though a resize copies every element - where does the constant come from?" A dynamic array grown by factor a when full copies about n/(a-1) elements across n appends, so the amortised copy cost per push is roughly 1/(a-1):

growth factor aamortised copies/pushcapacity wasted at peak
2.0~150%
1.5~233%
1.125~811%

CPython's list grows by about 1/8, which is why the bottom row looks the way it does (list_resize in Objects/listobject.c). Then the follow-up that matters in production: "The append path has a p99 latency SLO. Is amortised O(1) evidence you can cite?" No. Amortised bounds the total over any sequence, which is stronger than average-case because it assumes no input distribution - but it proves nothing about a single call, and one append that triggers a resize of 8 million elements is still O(n) once. That is the distinction worth testing, because "amortised" and "on average" get used interchangeably in interviews and only one of them survives a tail-latency argument.

Listen for three things: whether they name the invariant before the bound, whether they can say what breaks it, and whether they separate the guarantee (total work across a sequence) from the measurement (per-call latency at the sizes you actually run). A candidate who does all three can apply amortised analysis; one who only re-derives the accounting cannot.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How would you reason about the stack invariant in a system you own?

Answer

The 90-second version

I own a tracing ingestion service that rebuilds call trees from a flat stream of span start/end events. The invariant is one sentence: the stack is the chain of open spans, ordered by start time, and each is an ancestor of the next, so stack[-1] is the parent of the next span that starts.

Reasoning about it is three steps, in this order: state the invariant, prove each operation preserves it, then decide where to check it. The proof is what tells you which operations are allowed; the check is what tells you the stream you're being fed is the stream you assumed.

Proving it's preserved

Two operations, both by induction over the event stream. Base case: empty stack, vacuously a chain.

  • Start. The new span's parent is stack[-1] (or None if empty), so it is a child of the top. Its start time is later than the top's, so ordering holds. The chain extends by one link.
  • End. The ending span must be the top. If it isn't, the stream is malformed: a child ended before its parent, or an end arrived for a span that was never pushed. Popping the top leaves a prefix of the previous stack, which is still a chain in order.

That second case is the whole point. The invariant doesn't just describe the stack; it tells you the one input that breaks it, and that input is exactly what a real collector emits when it drops an end event or a clock skews.

Python
# Python 3.12
# Invariant: stack is the chain of open spans, ordered by start time,
# each an ancestor of the next. stack[-1] is the current parent.
def on_start(span, stack):
    span.parent = stack[-1].id if stack else None
    stack.append(span)

def on_end(span, stack):
    assert stack and stack[-1].id == span.id, "end out of order"
    stack.pop()

The assert is the invariant checked at the only point it can break. It's O(1), so it can run in production behind a sampling flag, not just in tests.

A trace

Eight events, timestamps in ms:

eventstack afterparent assigned
start A @0[A]None
start B @5[A, B]A
start C @12[A, B, C]B
end C @20[A, B]—
end B @30[A]—
start D @35[A, D]A
end D @40[A]—
end A @50[]—

D's parent is A, not B, because B already closed. That's the invariant doing the work: no timestamp comparison against a global "current span" variable, which is the bug you get when you skip the proof.

Failure modes and how you see them

  • Dropped end event. The stack never pops, depth grows without bound, and every later span gets the wrong parent. Detect with a gauge on max stack depth per trace and a counter spans_unmatched_end_total; a trace whose depth exceeds its span count is corrupt.
  • Out-of-order end. The assert fires. In production you don't crash the collector: you drop the end, increment the counter, and mark the trace as partial.
  • Clock skew. Starts and ends arrive in the right order but timestamps disagree. The stack discipline is fine; the invariant is silent on this, which is the signal that you're measuring the wrong thing.

When invariant-first is the wrong tool

It pays when the spec is known and the risk is a discipline bug: here, parent assignment. It doesn't pay when you're still discovering the spec, or when the invariant is trivially true and the real risk is elsewhere (the skew case above). The alternatives are property-based testing with Hypothesis, which generates event streams and checks the invariant after each one, and differential testing against a reference tree-builder. Property tests find the malformed streams; the production assert catches the ones your generator never thought of. If the invariant costs O(n) to check, keep it in tests only and rely on the counter in production.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does elements left on the stack matter, and where is it irrelevant?

Answer

Core answer. Elements left on the stack at the end are exactly the elements that were never popped. Whether that matters turns on one question: does the problem require an output for every position, or is the answer fully accumulated at pop time?

  • If every index needs an answer (next greater element, daily temperatures) leftovers matter. They are the elements with no answer, and you must write the sentinel.
  • If the answer is produced only when an element pops (trapping rain water, any pop-time aggregate) leftovers are irrelevant. They never popped, so they never contributed.

Why leftovers are exactly the unresolved elements. In a next-greater-to-the-right scan you keep a stack of indices whose answer is still unknown, in decreasing value order. When a[i] arrives, every stack top smaller than a[i] is popped and gets a[i] as its answer: a[i] is the first greater element to its right. An element survives to the end only if no later element was greater, i.e. it is a right-to-left maximum. Nothing greater ever came after it, so no answer exists; the sentinel is the only correct value.

Where they matter: next greater element. a = [2, 1, 3], out initialised to -1.

i=0: stack empty -> push 0            stack=[0]
i=1: a[1]=1 < a[0]=2 -> push 1        stack=[0,1]
i=2: a[2]=3 > a[1]=1 -> pop 1, out[1]=3
     a[2]=3 > a[0]=2 -> pop 0, out[0]=3
     stack empty -> push 2             stack=[2]
end: leftover 2, out[2] stays -1

out = [3, 3, -1]. Index 2 is the suffix maximum; -1 is correct. Drop the initialisation and out[2] is 0: a valid index, silently wrong.

Where they are irrelevant: trapping rain water. Water is added only when a taller bar pops a shorter one; the popped bar is the floor, the new bar is the right wall, the stack top below is the left wall.

a = [2, 0, 2]
i=0: push 0                          stack=[0]
i=1: a[1]=0 < a[0]=2 -> push 1        stack=[0,1]
i=2: a[2]=2 > a[1]=0 -> pop 1
     width  = 2 - 0 - 1 = 1
     height = min(a[0], a[2]) - a[1] = 2
     water += 2
     a[2]=2 not > a[0]=2 -> push 2     stack=[0,2]
end: leftovers 0, 2 — no right wall, no water

water = 2. The leftovers are ignored correctly: a bar with no taller bar to its right cannot hold water.

Trade-offs. Two ways to handle the mattering case:

  • Pre-initialise the output array to the sentinel. One line, no post-loop code. Risk: the sentinel must be right. 0 is a valid index, so use -1 or n.
  • Drain the stack after the loop. No sentinel to remember, but duplicates the pop logic and is easy to omit entirely.

Deciding criterion: if the output array is already allocated and the sentinel is unambiguous, pre-init. If the sentinel collides with valid values (you return indices and 0 is legal), drain.

Failure modes. Forgetting the sentinel passes any test where every element gets popped: a strictly increasing input pops everything, so the bug hides. A strictly decreasing input leaves every element on the stack and exposes it immediately. In largest rectangle in histogram the drain is not optional: remaining bars extend to the right edge, so you append a 0-height sentinel or drain with width = n - stack[-1] - 1. Skip it and you miss the full-width rectangle.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is stack-based backtracking state?

Answer

First I find the shared mutable state and list every mutation of it. In a backtracking PR that is usually a path list, a visited set, and an accumulator. Then I check that each mutation has an undo on every exit path: normal return, early return, and exception. That is the review; the rest is confirming the tests would catch it if the undo were missing.

Assumptions I state before commenting: is the state mutated in place or copied per branch, is the traversal recursive or an explicit stack, and what bounds the depth.

1. Undo adjacent and unconditional. A return, break, or continue between the push and the pop is the bug. In the snippet below the target branch returns after undoing; a version that returns before the pop leaks state into the parent frame.

2. Aliasing. results.append(path) stores a reference, not a snapshot. Every recorded result is the same list object, and it is empty by the time the caller reads it.

Python
def dfs(node, path, visited, results, graph, target):
    path.append(node); visited.add(node)
    if node == target:
        results.append(path)          # bug: reference, not copy
        path.pop(); visited.discard(node)
        return
    for nxt in graph[node]:
        if nxt not in visited:
            dfs(nxt, path, visited, results, graph, target)
    path.pop(); visited.discard(node)

Trace with graph = {0: [1, 2], 1: [], 2: []}, target = 2, starting at 0:

  • dfs(0): path=[0], visited={0}. Not target. Recurse into 1.
  • dfs(1): path=[0,1], visited={0,1}. Not target, no neighbours. Pop → path=[0], visited={0}.
  • Recurse into 2. dfs(2): path=[0,2], visited={0,2}. Target: results.append(path) stores the same list. Pop → path=[0].
  • Back in dfs(0): pop → path=[].

results == [[]]. The recorded path is empty because it aliases the list that was popped. results.append(path.copy()) gives results == [[0, 2]]. That is the comment I leave.

3. Recursion depth. Python's default limit is 1000 (sys.getrecursionlimit()), so a chain deeper than roughly 1000 nodes raises RecursionError. Ask what bounds the input depth. If nothing does, ask for an explicit stack or a justified sys.setrecursionlimit.

4. Order-dependence. A missing undo means visited never clears, so a node reachable by two paths is skipped on the second. The result then depends on neighbour order. Demand a test that shuffles adjacency and asserts the same result set, plus a diamond graph where one node is reachable two ways.

ApproachExtra memoryWhat breaks itWhen I ask for it
Undo in placeO(1) beyond the statea missed or conditional undo; aliasingdefault when depth is bounded
Copy state per branchO(depth) per branchallocation cost onlysmall state, undo logic hard to verify
Iterative explicit stackO(depth) on the heappopping state in the wrong orderdepth can exceed the recursion limit

Comments I leave: "this return skips the pop. Move the undo above it"; "append(path) needs path.copy()"; "what bounds depth here?"; "add a test that permutes neighbours and asserts an identical result set." I approve once the undo is unconditional on every exit path, results are snapshots, and a permutation test exists. If depth is unbounded, I ask for the explicit stack before approving.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does capacity and memory bounds interact with rollback, and where do people ignore that?

Answer

The 90-second answer. Rollback is a capacity consumer, not a capacity-neutral control operation. Every rollback mechanism depends on retained state: undo records, old row versions, the previous container image, the idempotency key, the log offset, and a memory or retention bound is a policy for discarding state. If the bound doesn't separate rollback-critical state from disposable state, it discards the thing rollback needs, and you find out at the moment you try to roll back, when the system is already degraded. Two shapes of bound bite differently: bounds that evict (LRU, TTL, log retention) silently delete the rollback target; bounds that reject or kill (OOM-kill, noeviction, max depth) destroy in-memory rollback state by terminating the process, so what you call a rollback is actually a crash.

Mechanism. Rollback state is proportional to work already done, not to remaining headroom. A transaction that has written 10M rows needs those versions retained until it commits or aborts; a saga that has run six steps needs six compensations; a deploy that has shipped needs the previous artifact. So the rollback path's peak demand lands exactly when free capacity is lowest. A bound sized for the steady state is sized for the wrong moment.

Where it breaks, concretely.

Eviction deletes the rollback target. Redis as an idempotency store:

maxmemory 2gb
maxmemory-policy allkeys-lru

Request 1: SET idem:abc NX EX 86400 → OK → apply side effect → client times out before the ack. Retry: SET idem:abc NX → the key was evicted under memory pressure → OK → apply again. The operation ran twice, and the rollback you thought the key guaranteed never existed. Detection: applied-operation count exceeds distinct request-ID count, or a ledger shows two rows for one key. Fix: idempotency keys do not belong in an evictable cache. Put them behind a unique constraint in a durable store, or run that instance noeviction.

Retention deletes the replay point. Kafka retention.bytes (default -1, unlimited) or retention.ms (default 604800000, 7 days). A burst pushes the offset you need to replay for rollback out of the log; the consumer then gets OffsetOutOfRange and cannot reconstruct the pre-rollback state.

GC deletes the artifact. kubelet defaults imageGCHighThresholdPercent=85, imageGCLowThresholdPercent=80. Node disk crosses 85%, kubelet garbage-collects images that aren't running: including the previous deployment's image. kubectl rollout undo then stalls in ErrImagePull if the registry also pruned it. Detection: rollout undo stuck, kubectl describe pod shows ErrImagePull.

BoundRollback impactDetection signal
LRU / TTL evictionDedup or undo key gone → double-applyApplied count > accepted count
Log retention (bytes/ms)Replay offset goneOffsetOutOfRange
Image GCRollback target goneErrImagePull on undo
OOM-kill / noevictionIn-memory undo lost → crash, not rollbackRestart with no rollback record

Where people ignore it. They size memory for the forward path and the steady state, then treat rollback as a control-plane operation that is always available. They set retention and eviction policies by cost (disk, RAM) without checking what the rollback path reads. And they conflate a crash with a rollback: an OOM-kill loses in-memory undo state, while a rollback replays it, so the two recoveries are not interchangeable.

Trade-off and deciding criterion. Keeping rollback state pinned costs memory and disk; letting it evict is cheaper until the first rollback. The criterion is whether rollback correctness is load-bearing: money movement, exactly-once side effects, or a compliance undo → pin the state and accept the cost. Best-effort rollback where a retry is harmless → eviction is fine. State which one you're in before choosing the bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What belongs in a runbook section on undo and history, and what does not?

Answer

First pin down which undo you mean. A runbook section covers operator-facing undo, rolling a production change back, not the end-user undo in the product UI. Assume a service where operators apply config changes and can revert them; the section is what an on-call engineer reads at 03:00 with no context.

The inclusion test is four questions: can they find the current state, undo to a target, verify it worked, and know when to stop and escalate? Anything that does not serve one of those four is design-doc material, not runbook material.

BelongsWhy
Exact command, flags, defaultsOperator runs it verbatim
Scope of what undo revertsConfig only? Data? Side effects like sent mail?
Retention windowUndo past it fails; operator must know before trying
Preconditions and guardsWhat the system checks vs what the operator must check
Verification query + expected output"It worked" is not evidence
List of irreversible operationsThe ones undo cannot take back
Propagation delayHow long until the revert is live everywhere
Escalation pathWho to page when undo fails twice
Does not belongWhere it goes instead
Undo-stack vs redo-stack mechanicsDesign doc
Tutorial on how undo worksOnboarding
Speculative failure modes with no detectionNowhere until you can detect them
Per-change-type walkthroughsLink the API reference
Rationale for why the system was built this wayDesign doc

A worked section for a hypothetical service cfgctl:

MARKDOWN
## Undo and history

List revisions (retained 90 days or 500 revisions, whichever first):
  cfgctl history --env prod --limit 20

Undo to revision R (reverts config only; does NOT re-run side effects):
  cfgctl undo --env prod --to R
  # blocks if a deploy is in flight; check: cfgctl status --env prod

Verify:
  cfgctl history --env prod --limit 1        # expect HEAD == R
  curl -s https://prod.internal/config | jq .revision   # expect R

Irreversible: undo past a `purge` revision cannot restore deleted secrets.
Retention: older revisions are gone; undo fails with E_NO_REVISION.
Propagation: reaches all nodes within 60 s (p99).
Escalate: #platform-oncall if undo fails twice.

The one boundary condition worth stating as an operator fact: after any new change, prior redo targets are gone. Trace it: history [A, B, C], undo to B (C becomes the redo target), apply D: the redo target C is dropped, so cfgctl redo now fails with E_NO_REDO. That single line belongs in the section; the stack explanation behind it does not.

Three failure modes to watch. A section that documents the data structure instead of the commands leaves the operator unable to act. A section that omits the retention window sends them chasing a revision that was pruned last week. A section that calls undo "safe" without listing irreversible operations is the one that turns a revert into an incident.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

How should on-call treat an alert that names the constant-time minimum stack as the cause?

Answer

The alert names a component, not a cause. "Constant-time minimum stack" is a code path: the thing that computes a running minimum over a push/pop sequence. On-call's job in the first two minutes is not to reason about the data structure; it is to confirm the symptom is real and user-visible, bound the blast radius, and pick the cheapest mitigation. Debug the algorithm after the page is quiet.

What the alert is actually pointing at. Two shapes, and they triage differently:

  • Correctness: get_min returns a stale or wrong value after pops, so whatever consumes it makes a wrong decision. A scheduler picking the wrong node, a rate limiter admitting the wrong request, a sliding-window aggregation reporting a floor that never occurred. This is a data-correctness page: it can silently corrupt downstream state, so it outranks a latency blip.
  • Resource: the per-entry running minimum is O(n) auxiliary memory. A workload that pushes without popping grows RSS linearly. This is a capacity alert; it pages only when headroom is gone.

The mechanism, so you know which one you are looking at.

Python
stack = []
def push(v): stack.append((v, v if not stack else min(v, stack[-1][1])))
def get_min(): return stack[-1][1]

Trace: push 3 → [(3,3)]; push 1 → [(3,3),(1,1)]; push 4 → [(3,3),(1,1),(4,1)]; pop → [(3,3),(1,1)], min 1; pop → [(3,3)], min 3. The single-variable variant returns 1 after that second pop: wrong, and it passes any test that never pops the current minimum.

Decision path.

  1. Check the SLO burn, not the component metric. If users are not affected, this is a ticket, not a page.
  2. If a deploy in the last hour touched that path, roll back first and investigate after. Rollback is the cheapest mitigation when the change is the suspect, unless the same deploy carried a migration, in which case rollback is not free and you mitigate forward.
  3. No recent deploy → suspect resource or workload shape. Cap stack depth, shed load, or restart to reclaim memory as a stopgap.
  4. Only then root-cause: reproduce the push/pop sequence, add the assertion that pops the current minimum.

Failure modes of the response itself. Treating the component name as the diagnosis and reading the algorithm while the service burns. Rolling back a change that also altered persisted state. And "watch it" on a correctness alert: a wrong minimum does not heal.

The alert tells you where to look, not why. Confirm the symptom, bound the blast radius, mitigate, then debug.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why array-backed versus linked stacks delays a ship date?

Answer

The 60-second version for product

The stack's backing store decides whether we pass the release gate. We built the request parser on a linked-node stack because push is worst-case O(1): no resize spike. That guarantee is real, and it costs us a heap allocation and a cache miss on every push. Under the load test the service holds p99 at 180 ms against a 50 ms gate, so the release is blocked. Swapping to an array-backed stack is about a day of code; the date moves by the re-run of the load test, not by the code.

What the choice actually changes

An array-backed stack keeps elements in one contiguous block and doubles the block when it fills. Pushes are amortised O(1): most are a pointer bump, and one in n pays a copy of the whole block. A linked stack allocates a node per push. Every push is O(1) worst case, and every push is also a call into the allocator and a jump to a new cache line.

Figures below are from a microbenchmark on one x86-64 host; read them as ratios, not absolutes.

Array-backedLinked nodes
Push, typical~1-2 ns~20-50 ns
Push, worst caseO(n) copy on resizeO(1)
Bytes per element8 + growth slack32 (glibc, 64-bit)
Allocations per 100k pushes~17 (doubling)100,000

The 32 bytes is the part people miss. An 8-byte value plus an 8-byte next pointer is a 16-byte request, and glibc rounds that up to a 32-byte chunk on 64-bit. The array holds the same element in 8 bytes.

Why it shows up as a date, not a bug

Our parser holds a stack per in-flight request, depth up to 100k on pathological input. Array-backed, that is 800 KB, doubling to 1.6 MB during a resize. Linked, it is 3.2 MB and 100k live allocations per request. At 2,000 req/s across 32 threads the allocator becomes the contended resource: p99 goes from 40 ms to 180 ms once the arena lock saturates. Nothing is incorrect. The gate is a latency gate, and we miss it.

What I need from you

Two options. Swap to the array-backed stack: one day of code, then the load-test re-run and a canary, so three days of calendar. Or keep the linked stack and spend a week on allocator tuning, per-thread arenas, with no guarantee it clears 50 ms. I would take the swap. The worst-case O(1) we paid for is a guarantee we do not need: depth is already bounded by the input size we cap at 100k.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about stack overflow as a security boundary?

Answer

The experiment: one request, two arms, against the real endpoint.

Send a payload nested about 1000 deep and watch two things: the status code, and whether the worker is still serving afterwards. That is the whole experiment; everything else is inference.

Arm A, default runtime:

Python
import json, sys
print(sys.getrecursionlimit())            # 1000
try:
    json.loads("[" * 100_000 + "]" * 100_000)
except RecursionError as e:
    print("caught", type(e).__name__)     # caught RecursionError
print("alive")                            # alive

Trace: the C scanner enters one frame per [ and calls Py_EnterRecursiveCall each time. At depth 1000 it raises RecursionError, an ordinary Python exception. Caught, printed, process continues. So on a default CPython the failure is a catchable exception, not a dead worker, if your service returns 500 here, that is your handler, not the interpreter.

Arm B, raise the limit and repeat:

Python
import sys
sys.setrecursionlimit(1_000_000)
import json
json.loads("[" * 100_000 + "]" * 100_000)

On CPython 3.11 and earlier this aborts with SIGSEGV (exit status -11): 100k C frames blow the 8 MiB default thread stack, and a segfault is not catchable. On 3.12+ the same code raises RecursionError again, because 3.12 added a separate C recursion limit that sys.setrecursionlimit() cannot raise. Check which runtime you are on before drawing a conclusion.

What changes my mind. If Arm A returns a clean 4xx and the worker keeps serving, the boundary for that endpoint is the parser's depth check, and I stop calling it a security bug there. If Arm B segfaults, the only thing between an attacker and a hard crash is a policy constant of 1000: a boundary you own, not one the language gives you.

Alternatives, and when each is wrong.

MoveStopsWrong when
Depth pre-check / parser depth limitRecursionError and C-stack blowup on that pathOnly that path: regex, YAML, XML and template engines each need their own
Parse in a worker with a small stack and a timeoutBlast radius: one worker dies, supervisor restartsYou still pay a process hop and latency; contains the crash, does not prevent it
Raise the recursion limitNothingActively worse on ≤3.11: turns a catchable exception into a segfault
seccomp / separate sandboxed processThe whole classCost and ops burden; only worth it when you cannot bound the input

Do not catch RecursionError and continue in the same frame: the stack is still nearly exhausted, so the handler itself can re-raise. Reject at the edge before parsing.

Detection. Count RecursionError per endpoint and worker restarts; a 500 spike with a fixed payload shape is the signature. A worker that dies with no traceback is the segfault case.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document recognising a stack problem so the next owner can operate it?

Answer

Hand the next owner three artefacts, not a paragraph: the invariant as a checkable sentence, the recognition rule as a question with a counterexample for each wrong answer, and a test that fails when the invariant breaks. "Stacks are LIFO" is what they already know; what they cannot reconstruct is why this code chose one and what breaks if it didn't.

Invariant, stated about contents. "The stack holds indices of elements whose next greater element has not been seen; their values decrease from bottom to top." That is assertable in a debug build:

Python
assert all(nums[stack[i]] > nums[stack[i + 1]] for i in range(len(stack) - 1))

Recognition rule as one question. Does the next input resolve the most recent unresolved item, and is that resolution final? If resolution can be revisited, or the oldest unresolved item is the one that expires, a stack is the wrong structure.

SignalStructureDeciding reason
Next input resolves the most recent unresolved item; finalstackLIFO; each item pushed once, popped at most once
Same, but items also expire by position or timemonotonic dequemust evict from the front, which a stack cannot do
Resolution happens in arrival orderqueueFIFO
Resolved items get revisited or correctedneitherno single-pass invariant exists

Worked trace, smallest distinguishing input. Next-greater-element on [2, 5, 3, 4], checked on CPython 3.12:

Python
def next_greater(nums):
    res = [-1] * len(nums)
    stack = []                      # indices, values decreasing bottom->top
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            res[stack.pop()] = x
        stack.append(i)
    return res

i=0 x=2: push 0 -> [0]. i=1 x=5: 2<5, res[0]=5, pop; push 1 -> [1]. i=2 x=3: 5<3 false, push 2 -> [1,2]. i=3 x=4: 3<4, res[2]=4, pop; 5<4 false, push 3 -> [1,3]. Result [5, -1, 4, -1].

Failure modes with detection. The wrong structure usually still passes the happy path. A queue accepts "([)]" as balanced because it pairs ( with ) and [ with ]; a stack rejects it at the first ). Put that string in the test corpus: it is the input that separates them. For the monotonic case the failure signature is a wrong answer on a non-monotone prefix, so the property test is the detector:

Python
brute = lambda nums: [next((y for y in nums[i+1:] if y > x), -1)
                      for i, x in enumerate(nums)]
for _ in range(1000):
    nums = [random.randint(-5, 5) for _ in range(random.randint(0, 12))]
    assert next_greater(nums) == brute(nums)

What the next owner operates on. Two metrics: pushes and pops. Over n inputs a correct monotonic stack pushes exactly n and pops at most n, so pops > pushes means the invariant is broken. Max depth is the memory ceiling: a strictly decreasing stream of 10^6 elements holds 10^6 indices, which is the number to size against. Document the rejected alternative (deque, queue) and the input that would have chosen it, so the next owner can tell a bug from a deliberate choice.

Curated: · Written: · Reviewed:

Difficulty: Medium