Valid Parentheses, visualized step by step

Easy One of the Blind 75 interview problems (LeetCode 20). Technique: stack. Solution in Python, explained at every step.

The problem

You get a string made of the brackets ( ) [ ] { }. It is valid when every opening bracket is closed by a bracket of the same type, and the brackets close in the right order: the one opened last closes first.

Example: ([]{()}) is valid. ([)] is not: ) arrives while [, opened later than (, is still open.

The string ([]{()}) with each bracket joined to its partner by a line underneath; the lines sit one inside another. Answer: yes. The string ([)] with ( joined to ) and [ joined to ]; the two lines cross. Answer: no.
Joined to their partners, the brackets of a valid string nest. In ([)] the pairs would cross.

Try it yourself first: LeetCode 20 ↗. Then step through the solution below.

Brute force

Delete adjacent pairs, (), [] and {}, again and again, and call the string valid if nothing is left. One pass over the string is O(n), and a pass may remove a single pair, as in ((((…)))), so it can take n / 2 passes: O(n2) time.

The key insight

The bracket that must close next is always the one opened most recently. So there is no need to look at the whole string again: keep the brackets still open, in the order they came, and compare a closing bracket with the last of them only.

That is exactly a stack. An opening bracket is pushed; a closing bracket must match the top, which is then popped. The string is valid if no closing bracket finds a wrong top or an empty stack, and the stack is empty at the end.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Valid Parentheses, step by step

Python

def is_valid(brackets):    partner = {')': '(', ']': '[', '}': '{'}    stack = []    for ch in brackets:        if ch in '([{':            stack.append(ch)        elif stack and stack[-1] == partner[ch]:            stack.pop()        else:            return False    return not stack
All steps as text
  1. The string brackets has 8 brackets of three kinds. Does every bracket close, in the right order?
  2. partner maps each closing bracket to its opening one. stack starts empty: it will hold the open brackets, latest on top.
  3. ch takes the first bracket, the round (. It opens a pair: push it.
  4. The square bracket [ opens another pair: push it on top.
  5. The bracket ] closes a pair. The top is [, its partner: pop it.
  6. The curly bracket { opens another pair: push it on top.
  7. The round bracket ( opens another pair: push it on top.
  8. The bracket ) closes a pair. The top is (, its partner: pop it.
  9. The bracket } closes a pair. The top is {, its partner: pop it.
  10. The bracket ) closes a pair. The top is (, its partner: pop it. The stack is empty again.
  11. The string is over and the stack is empty: every bracket closed, in the right order. The answer is yes.
  12. Each bracket was pushed or popped once: one pass, O(n) time.
Valid Parentheses, step by step. Last step: Each bracket was pushed or popped once: one pass, O(n) time.

Note

Python has no stack class: a list is one, with append and pop at its end, both O(1). In Java the old Stack class is synchronized and slower, so ArrayDeque with push and pop is the usual choice; C++ has std::stack.

Complexity

ApproachTimeSpace
Brute force: delete adjacent pairs until none is leftO(n2)O(n)
Stack, one pass this pageO(n)O(n)
  • Time: O(n). Each character is looked at once, and pushing and popping are O(1).
  • Space: O(n). A string of opening brackets only puts all of them on the stack.

Edge cases

  • An empty string: the loop never runs, the stack is empty, and the function returns True.
  • A closing bracket with nothing open, like )(: the stack is empty at ), so the function returns False at once.
  • The wrong type, like (]: the top is (, but ] needs [, so the function returns False.
  • Brackets left open, like ((: the loop ends with two brackets on the stack, so not stack is False.

Note

A quick exit: every bracket needs a partner, so a string of odd length can never be valid. Many solutions answer no before the loop. It saves time on such strings, but the time stays O(n).

When the answer is no

The same code on the statement's ([)], where two pairs cross. Press → for each step.

Valid Parentheses, when the answer is no

Python

def is_valid(brackets):    partner = {')': '(', ']': '[', '}': '{'}    stack = []    for ch in brackets:        if ch in '([{':            stack.append(ch)        elif stack and stack[-1] == partner[ch]:            stack.pop()        else:            return False    return not stack
All steps as text
  1. The string brackets has 4 brackets of two kinds. Does every bracket close, in the right order?
  2. partner maps each closing bracket to its opening one. stack starts empty: it will hold the open brackets, latest on top.
  3. ch takes the first bracket, the round (. It opens a pair: push it.
  4. The square bracket [ opens another pair: push it on top.
  5. The bracket ) closes a pair, but the top is [, not its partner (: the answer is no.
  6. The pairs cross: [ was opened last, so it must close first. One wrong closing bracket is enough.
Valid Parentheses, when the answer is no. Last step: The pairs cross: [ was opened last, so it must close first. One wrong closing bracket is enough.

Try it: put Valid Parentheses together step by step

The blocks below are steps of Valid Parentheses in words, and one of them does not belong. Put the right ones in order and check: your algorithm runs on ([]{()}), ([)] and ((, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Valid Parentheses together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. One of them doesn't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

What if there is only one bracket type? Then the stack would only ever hold copies of (, so its height is all that matters: a counter goes up on ( and down on ), the string fails if it ever drops below zero, and it is valid if it ends at zero. Still O(n) time, but O(1) space.

The data structure behind it

  • Stack: push, pop and the top in O(1), and the balanced parentheses example from the app.
  • Stack vs Queue: the same operations on both, and why the order differs.