Stacks

Last-in, first-out. The structure behind function calls, undo, parsing and depth-first search.

Beginner 2 min readLesson 4 of 16 Interview Q&A

A stack is a collection where you can only add (push) and remove (pop) at one end — the top. The last element pushed is the first one popped: LIFO (last in, first out). Think of a stack of plates.

7← top294
push adds to the top; pop removes from the top. All O(1).

Operations

OperationDescriptionTime
push(x)Add x on topO(1)
pop()Remove & return topO(1)
peek() / top()Read top without removingO(1)
isEmpty()Any elements?O(1)

A stack is usually backed by a dynamic array (push/pop at the end) or a linked list (push/pop at the head).

import java.util.ArrayDeque;
import java.util.Deque;

// Prefer ArrayDeque over the legacy synchronized java.util.Stack
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.peek();      // 2
stack.pop();       // 2
stack.isEmpty();   // false

Where stacks appear

  • The call stack. Each function call pushes a stack frame (locals, return address); returning pops it. Infinite recursion → StackOverflowError. See Memory: stack & heap.
  • Undo / back button. Push each action; undo pops the latest.
  • Parsing. Matching brackets, evaluating expressions, HTML tag matching, compilers.
  • DFS. Iterative depth-first search uses an explicit stack. See Graph traversal.
  • Monotonic stacks for "next greater element" style problems. See Monotonic stack.

Classic problem: valid parentheses

Push every opener; for every closer, the top of the stack must be its matching opener.

boolean isValid(String s) {
    Deque<Character> st = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        if (c == '(') st.push(')');
        else if (c == '[') st.push(']');
        else if (c == '{') st.push('}');
        else if (st.isEmpty() || st.pop() != c) return false;
    }
    return st.isEmpty();
}

Classic problem: min stack

Support getMin() in O(1). Keep a second stack holding the minimum at each depth.

class MinStack {
    private final Deque<int[]> st = new ArrayDeque<>(); // [value, minSoFar]
    void push(int x) {
        int min = st.isEmpty() ? x : Math.min(x, st.peek()[1]);
        st.push(new int[]{x, min});
    }
    void pop()   { st.pop(); }
    int top()    { return st.peek()[0]; }
    int getMin() { return st.peek()[1]; }
}

Evaluating expressions

Postfix (Reverse Polish) notation is evaluated with one stack: push numbers; on an operator, pop two, apply, push the result. 3 4 + 2 * → 14. Infix expressions are converted to postfix with Dijkstra's shunting-yard algorithm (two stacks: operators and output).

Key takeaways
  • Stacks are LIFO with O(1) push/pop/peek.
  • Use ArrayDeque in Java, a list in Python, an array in JS/TS.
  • Reach for a stack when the most recent unmatched item matters: brackets, undo, recursion → iteration, DFS, next-greater-element.
Interview questions
QImplement a queue using two stacks.medium

Push onto an in stack. To dequeue, if out is empty, pop everything from in onto out (reversing order), then pop from out. Each element moves at most twice → amortized O(1) per operation.

QWhy does deep recursion cause a stack overflow, and how do you avoid it?easy

Each call consumes a frame on a fixed-size thread stack (often ~512 KB–8 MB). Avoid it by converting the recursion to iteration with an explicit heap-allocated stack, using tail recursion where the language optimises it, or reducing depth (e.g. recurse on the smaller half in quicksort).

QDaily temperatures: for each day, how many days until a warmer one?medium

Monotonic decreasing stack of indices. For each day, pop while the top is colder than today, setting answer[popped] = today - popped, then push today. O(n).