Stack · Pattern 1 of 1

Stack problems: match, cancel, evaluate, nest

Push what is still open or pending; when the next item resolves it, pop. Brackets, cancelling neighbours, calculators and nested decoding are all this one move.

6 variations · 24 problems · 11 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Valid brackets or the minimum fix to make them valid
  • Neighbours that cancel or collide
  • Evaluate an expression with + − × ÷ and parentheses
  • Nested structures like 3[a2[c]] or a file path

The template

Stack Basics
boolean isValid(String s) {
    Deque<Character> st = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        if (c == '(') st.push(')');            // push the closer we expect
        else if (c == '[') st.push(']');
        else if (c == '{') st.push('}');
        else if (st.isEmpty() || st.pop() != c) return false;
    }
    return st.isEmpty();                       // nothing left open
}

int evalRPN(String[] tokens) {
    Deque<Integer> st = new ArrayDeque<>();
    for (String t : tokens) {
        if ("+-*/".contains(t) && t.length() == 1) {
            int b = st.pop(), a = st.pop();    // second pop is the left operand
            st.push(t.equals("+") ? a + b : t.equals("-") ? a - b : t.equals("*") ? a * b : a / b);
        } else st.push(Integer.parseInt(t));
    }
    return st.pop();
}

The variations

  1. 1Match and fix brackets

    Push openers (or the closer you expect); a closer must match the top. To fix a string, push indexes and delete whatever is left unmatched. With * wildcards, track a range of possible open counts.

  2. 2Cancel or collide with the top

    Compare each new item with the top: equal letters cancel, asteroids moving toward each other collide, "C" removes the last score. Keep counts on the stack for "k adjacent".

  3. 3Evaluate expressions

    Postfix: numbers go on the stack, an operator pops two. Infix: push signed numbers, apply × and ÷ to the top at once, recurse (or push state) at each parenthesis, sum at the end.

  4. 4Nesting

    On "[" (or a start event) push the current state and begin a new one; on "]" pop and combine. Paths, nested lists and function timelines nest the same way.

    Worked example Decode String Medium Read the solution
  5. 5Design with stacks

    A min stack stores the minimum alongside each value. Two stacks make a queue (move items only when the output stack is empty); a queue rotated after each push makes a stack.

  6. 6More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Python // floors negative numbers (−7 // 2 = −4); RPN wants truncation, so use int(a / b).
  • Pushing indexes vs characters: push indexes when you must delete or measure later.
  • Calculators: applying * and / before + and − needs either two stacks or "push signed numbers, collapse * and / immediately".
Back to Stack →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.