BeginnerStack

Matching brackets with a stack

Push every opening bracket; on a closing one, the top of the must be its partner. Last opened, first closed.

The idea

Brackets close in the reverse order they open: the most recently opened must close first. That “last in, first out” order is exactly what a stack gives you.

At the end the stack must be empty, or something was opened and never closed.

Worked example

“( [ ] )” and “( ]”

  1. ( → push → [(] [ → push → [(, [] ] → top is [ ✓ pop ) → top is ( ✓ pop → empty → valid
  2. ( → push ] → top is ( but needs [ → invalid

In code (Python)

def is_valid(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:
            stack.append(ch)
    return not stack

time, O(n) space.

How to spot it

  • Nested structure: brackets, tags, “undo the most recent”, evaluating expressions.

Common mistakes

  • Popping from an empty stack on input like “)”.
  • Forgetting the final emptiness check, so “((” passes.

Practise the ideas first

Practise it

Go further