Skip to the page

Linear patterns · core

Stacks and queues in JavaScript

A stack (last in, first out) matches nested or 'most recent' things like brackets, undo and expression parsing, and a queue (first in, first out) drives BFS. In JavaScript, an array with push and pop is a good stack, but shift() is O(n), so a queue needs a head index.

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 → O(n).
  • Expression evaluation (+ − * /): keep a stack of terms; apply * and / immediately to the top; sum at the end. Use Math.trunc for integer division. Parentheses: push the current result and sign.
  • Queue with two stacks: push to 'in'; when 'out' is empty, move everything from 'in' to 'out'; amortised O(1).
  • Stack in JavaScript: push, pop, and stack.at(-1) (or stack[stack.length - 1]) to peek. pop() on an empty array returns undefined; it does not throw. Queue: keep a head index and read q[head++], because shift() moves every element (O(n)).
  • Frontend links: undo/redo stacks, browser history, nested tag validation, the call stack.

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: ']' crashes or returns undefined; check first.

  • Mistake: eval() is fine for a calculator

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

  • Mistake: stack[-1] is the top

    Fix: it reads a property named '-1' and is undefined; use stack.at(-1).

Easy to hard

Questions interviewers ask, easy to hard

  1. Valid parentheses.
  2. Validate nested HTML 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