Skip to the page

Linear patterns · core

Stacks and queues

A stack (last in, first out) matches nested or 'most recent' things like brackets, undo and expression parsing, a monotonic stack finds the next greater element in O(n), and a queue (first in, first out) drives BFS.

The notes

What you must know

  • Valid brackets: push openers; on a closer, the top must be its opener; valid only if the stack is empty at the end. Odd length is an early exit.
  • Monotonic stack: keep indices with decreasing values; when a bigger value comes, pop and record it as their 'next greater'. Each index is pushed and popped once, so it is O(n).
  • Expression evaluation (+ - * /): keep a stack of terms; apply * and / at once to the top; sum the stack at the end. For parentheses, push the current result and sign. Division must truncate toward zero: Java and C++ do it with /; in Python use int(a / b) because // rounds down.
  • Queue with two stacks: push to 'in'; when 'out' is empty, move everything from 'in' to 'out'; amortised O(1).
  • In Java use ArrayDeque for both a stack (push, pop, peek) and a queue (offer, poll); in Python use a list as a stack and collections.deque as a queue; in C++ use std::stack and std::queue or a vector as a stack.
  • Real uses: undo and redo, browser history, nested tag validation, the call stack itself.

The red pen

Common traps: mistake → fix

  • Mistake: Counting brackets is enough

    Fix: '([)]' has equal counts but is invalid.

  • Mistake: Pop without checking empty

    Fix: a closer with an empty stack crashes (Java EmptyStackException or NoSuchElementException, Python IndexError, C++ undefined behaviour); check first.

  • Mistake: Using eval for a calculator is fine

    Fix: it is a security risk and is not what the interviewer wants.

Easy to hard

Questions interviewers ask, easy to hard

  1. Valid parentheses.
  2. Validate nested tags like <div><span></span></div>.
  3. Next greater element for each item, in O(n).
  4. Evaluate '3+2*2' without eval; then add parentheses.
  5. Implement a queue with two stacks; what is the amortised cost?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview