Valid Parentheses

EasyStackLeetCode 20 ↗World 1-2
0:00 / 0:00

Check that every bracket is closed by the right type, in the right order. Push each opener, and match each closer against the top of the stack.

▼

The problem

Given a string of ()[]{}, decide whether it is valid: every opener is closed by a closer of the same type, in the right order.

Example: {[()]}() is valid.

def is_valid(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in s:
        if ch in pairs:          # a closer
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:                    # an opener
            stack.append(ch)
    return not stack
TRY IT ON LEETCODE ▶

The solution

def is_valid(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in s:
        if ch in pairs:          # a closer
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:                    # an opener
            stack.append(ch)
    return not stack

Transcript

Valid Parentheses. You get a string of brackets: round, square and curly. Is it valid? Every opener needs a closer of the same type, and they must close in the right order, like boxes nested inside boxes.

The tempting shortcut is to count them. Take round, square, close round, close square. There's one of each, so the counts match. But the round closer arrives while the square is still open inside it. That string is invalid, and counting can't tell.

What matters is order. A closer must match the most recent opener that's still open. Last opened, first closed: that's a stack. Push each opener on top. When a closer arrives, look at the top. If it's the same type, pop it off and move on.

Let's play a valid one: curly, square, round, the three closers, then one more round pair. Curly, square and round go on the stack. The round closer meets round on top: pop. Square meets square: pop. Curly meets curly: pop. The stack is empty again. Then round goes on, and its closer takes it off. Nothing is left, so it's valid.

It can fail in three ways. A closer can meet the wrong type on top, like round meeting square. A closer can arrive when the stack is empty, with nothing to close. Either way, stop right there: invalid. And when the string ends, any opener still on the stack was never closed. That's invalid too.

In code, a small dictionary maps each closer to its opener. Loop over the characters. For a closer, if the stack is empty, or the opener it pops isn't its partner, return false. Anything else is an opener, so push it. After the loop, return whether the stack is empty.

Each bracket is pushed and popped at most once, so the time is order n. In the worst case, all openers, the stack holds every one of them, so the space is order n too.

Push the openers, match the closers, finish empty. That's Valid Parentheses.