Android & iPhone apps are coming soon. Log in for a plan and reminders made for you β†’

BeginnerStack

Matching brackets with a stack

Push every opening bracket; on a closing one, the top of the stack 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

O(n) 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 it

Go further