Python coding

Brackets that close in order

s is a line of text, such as a snippet of code. Return True if its brackets are well formed: every (, [ and { is closed later by a bracket of the same kind, and each closing bracket closes the most recently opened one that is still open. Characters other than ()[]{} don't matter, so a line without brackets is well formed.

Aim for one pass over s.

Besides the tests, one large input (30,000 nested brackets) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • brackets_ok("if (a[i] == b[0]) { go(); }") → true
  • brackets_ok("([)]") → false
  • brackets_ok("{[()()]}") → true
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Counting opens and closes is not enough: ([)] has matching counts. The bracket that must close next is always the most recently opened one.

Hint 2

Push every opening bracket. On a closing one, the stack must not be empty and the top you pop must be its partner. At the end the stack must be empty.

Solution and why it works
pythonO(n) · O(n)
def brackets_ok(s: str) -> bool:
    opener = {")": "(", "]": "[", "}": "{"}
    stack = []                      # brackets still open, the latest on top
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in opener:
            if not stack or stack.pop() != opener[ch]:
                return False        # nothing open, or the wrong kind
    return not stack                # anything left was never closed

The last bracket opened is the first one that must close: exactly a stack's last-in, first-out order. Each character is pushed or popped at most once, so the pass is O(n). Three ways to get it wrong: counting brackets instead of matching their kinds (([)]), popping an empty stack on a stray closer ()(), and ignoring openers still on the stack at the end ((().