Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Valid Parentheses

EasyLeetCode 20 ↗

The problem, in one line. Given a string made only of round, square and curly brackets, say whether every opener is closed by the right kind of closer in the right order. LeetCode 20.

The tell. Things open inside other things and must close in reverse order. Whenever the question is “which opener is still waiting, most recent first?”, the answer is a stack.

The wrong first idea

Count. Add one for each opener, subtract one for each closer, and call the string valid if the total ends at zero.

def is_valid(s):
    return s.count("(") == s.count(")") and s.count("[") == s.count("]") and s.count("{") == s.count("}")

It says yes to ([)], because every kind balances. Counting forgets order. When the ) arrives, the most recent open bracket is [, and a count cannot tell you that.

The invariant

The full walkthrough is in the clinic Clinic #07: Valid Parentheses. This card is its one page.

Read left to right. Push every opener. On a closer, pop and compare.

flowchart LR
  A["( push<br/>stack: ("] --> B["[ push<br/>stack: ( ["]
  B --> C[") pop gives [<br/>needs ("]
  C --> D["mismatch: false"]

The sentence that stays true every step: the stack holds exactly the openers that are still unclosed, newest on top. A closer can only legally close the newest one, so that is the only one worth comparing.

The solution

def is_valid(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    st = []
    for c in s:
        if c in pairs:
            if not st or st.pop() != pairs[c]:   # closer must match the newest opener
                return False
        else:
            st.append(c)                         # opener waits on the stack
    return not st

print(is_valid("()[]{}"))
print(is_valid("(]"))
print(is_valid("(("))
True
False
False
func isValid(s string) bool {
	pairs := map[rune]rune{')': '(', ']': '[', '}': '{'}
	st := []rune{}
	for _, c := range s {
		if open, ok := pairs[c]; ok {
			if len(st) == 0 || st[len(st)-1] != open { // closer must match the newest opener
				return false
			}
			st = st[:len(st)-1]
		} else {
			st = append(st, c) // opener waits on the stack
		}
	}
	return len(st) == 0
}

Same three calls print true, false, false.

Complexity

  • Time O(n): each character is pushed at most once and popped at most once.
  • Space O(n): a string of only openers puts all of them on the stack.

Traps

  • Returning true when the loop ends without checking the stack. (( never mismatches, so only the final emptiness test rejects it.
  • Popping from an empty stack. ) alone crashes in Python and panics in Go unless you test for empty first.
  • Comparing the closer to the wrong side of the map. Map closer to opener, so (] fails at the ] instead of silently passing.

Next in the ladder

Remove All Adjacent Duplicates In String uses the same stack for a gentler job: instead of matching openers to closers, a letter cancels the letter on top of the stack when they are equal.