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.

Overview

Curated: · Written: · Reviewed:

Stacks

In one line

A LIFO structure where only the top is reachable, so each input resolves the most recent unresolved item. Reach for it when nesting, matching, nearest-previous or undo history decides the answer.

Key definitions

  • Invariant: what the stack holds at every step. State it before the push and pop rules.
  • Monotonic stack: kept sorted by value. A new element pops every top it dominates and resolves them.
  • Sentinel: a value outside the input domain, appended so the loop drains the stack.
  • Two-stack queue: an inbox and an outbox. Transfer only when the outbox is empty.
  • Shunting-yard: infix to postfix using an operator stack ordered by precedence and associativity.
  • Amortised O(1): average cost over a sequence, where occasional resizes cost O(n).

Formulas and complexity

pushes=n,  pops≤pushes⇒total work O(n)pushes = n, \; pops \le pushes \Rightarrow \text{total work } O(n)

Right-associative exponent, written as the code 2 ^ 3 ^ 2:

232=29=5122^{3^{2}} = 2^{9} = 512

Left-associative division, written as the code 8 / 4 / 2:

(8/4)/2=1(8 / 4) / 2 = 1

Hypothetical profile: max depth=2 MiB256 B=8,192 levelsmax\ depth = \frac{2\ \text{MiB}}{256\ \text{B}} = 8{,}192\ \text{levels}

How it works

  • Each input either pushes itself (still unresolved) or pops the entries it resolves.
  • The invariant fixes which entries are resolved, so the newest unresolved item resolves first.
  • Each element is pushed once and popped at most once, which gives the linear bound.
  • In postfix, pop the right operand first: b = pop(); a = pop(); push(a op b). For 5 1 2 + 4 * + 3 - the stack goes [5,1,2], [5,3], [5,3,4], [5,12], [17], [17,3], [14], so the service returns 14.
yes no read x top < x? pop top, answer for top = x push x next element

When to use and when not to

QuestionStack?Why
Matching nested delimitersYesThe newest opener closes first
Next greater or smaller elementYes, monotonicEach index is pushed and popped once
Undo and redoYesLIFO history; a new action clears redo
Shortest path, unweightedNo, use a queueA stack finds a path, not the shortest one
Interrupt path with a 2 µs budgetLinked, pooled nodes onlyArray resize copies 65536 pointers in about 30 µs
Recursion over untrusted nestingExplicit stack with a depth limitThe runtime stack is small and fixed

Traps interviewers probe

  1. Popping an empty stack on a closer. Fix: check if not stack: return False before the pop. Unbalanced input is a domain answer, not an exception.
  2. Popping operands in the wrong order. Fix: pop the right operand first. 5 3 - gives 2; reversed pops give -2, while + still passes, which hides the bug.
  3. Storing values instead of indices in a histogram pass. Fix: store indices, because the width of a popped bar runs from the element below it to the current index. Append a 0 sentinel so the stack drains.
  4. Transferring on every dequeue in the two-stack queue. Fix: transfer only when the outbox is empty. Pushing 1, 2, 3, popping, pushing 4 and popping three times returns 1, 4, 2, 3 under the buggy version.
  5. Assuming a bigger limit fixes recursion. Fix: convert to an explicit stack. Raising sys.setrecursionlimit or -Xss moves the failure without removing it, and CPython does not eliminate tail calls, so total(xs, acc) still grows the stack linearly.

Interview tips

Open with the invariant: "The stack holds the unresolved items, newest on top, and each input resolves the entries it dominates."

Expect these follow-ups:

  • Why is a nested pop loop linear? Count pushes, not loop bounds.
  • Why indices rather than values? The answer needs a distance.
  • What if the input is untrusted? Bound the depth and reject past it.
  • Array or linked? Amortised copies win on throughput; a pooled linked stack wins on worst-case latency.
  • Why not a stack for shortest path? On S to G the stack returns S, B, C, D, G, five nodes, where S, A, G is two edges. A queue gives the edge-count guarantee.

30-second outline:

  1. State the invariant.
  2. Derive push and pop from it.
  3. Each element is pushed once and popped once, so O(n).
  4. Name the edge case: the sentinel or the empty-stack guard.
  5. Name one trade-off: array versus linked, or stack versus queue.

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.