Algorithms · Stacks
Valid Parentheses
Is every bracket closed by the right kind, in the right order?
The problem
Return True if every bracket in s is closed by the same kind of bracket, in the right order. "([])" is fine; "([)]" is not.
balanced("()")→Truebalanced("()[]{}")→TrueStart with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def balanced(s):take a string of brackets while True:keep crossing out pairs… for i in range(len(s) - 1):look along the string, left to right if s[i:i + 2] in ("()", "[]", "{}"):a matching pair side by side? s = s[:i] + s[i + 2:]cross it out breakand start looking again from the beginning else:went all the way along without finding a pair return s == ""balanced if nothing is leftNow ask: what if there were a billion?
Every code editor, compiler and browser does this to check your brackets as you type. Python’s own tokenizer keeps a stack of open brackets; that’s how it can tell you “'(' was never closed”.
Aim for O(n)🧩 classic
Think it through
In “([{”, the next closer must match which opener?
- “(”, the first one
- “{”, the most recent one
Show the answer
“{”, the most recent one. The last one opened is the first one that must close. Last in, first out.
What keeps the most recent unclosed opener on top?
- A stack
- A queue
Show the answer
A stack. Push openers, and on a closer pop the top and check it matches. Your code editor, a browser parsing HTML, and Python reading your code all do this.
Stuck? 3 nudges, smallest first
- Deeply nested brackets like
((((()))))make the obvious way walk halfway along the string for every single pair it crosses out. - The most recent unclosed opener is the one the next closer must match. “Most recent” is a stack.
- Push openers. On a closer, pop the top and check it’s the matching opener. At the end, the stack must be empty.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def balanced(s):take a string of brackets pairs = {")": "(", "]": "[", "}": "{"}each closer and the opener it needs stack = []openers still waiting to be closed for ch in s:read the brackets left to right if ch in pairs:a closer? if not stack or stack.pop() != pairs[ch]:no opener waiting, or the wrong kind? return Falsenot balanced else:an opener stack.append(ch)put it on top of the pile return not stackbalanced if nothing is left waitingWhere it’s used for real
Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.