Step by step · Python and C++

Valid parentheses with a stack, visualized

Checking whether brackets are balanced (LeetCode 20) is the classic first stack problem. The rule “the most recent unclosed bracket must close first” is exactly last-in, first-out.

How it works
text = "{[()()]}"
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
balanced = True

for ch in text:
    if ch in "([{":
        stack.append(ch)
    else:
        if not stack or stack.pop() != pairs[ch]:
            balanced = False
            break

print(balanced and len(stack) == 0)

How the valid parentheses check works

Scan the string once. Push every opening bracket. For a closing bracket, the stack must be non-empty and its top must be the matching opener; pop it and carry on. Anything else means the string is invalid. At the end the string is valid only if the stack is empty — anything left over was opened and never closed.

The Python example checks "{[()()]}", which is balanced.

What to watch for when it runs

  1. The stack is drawn as a stack, growing and shrinking as brackets are pushed and popped.
  2. It is deepest at the innermost bracket and empties completely by the end.
  3. Change the input to "{[(])}" in the editor and run it again to see the mismatch caught.

Time and space complexity

Time
O(n)
Space
O(n)

One pass over the string. In the worst case — all openers — every character is on the stack at once.

Stuck on your own version?

Paste it into the visualizer and watch your own code run, line by line — bugs included.