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 pairs would cross.Try it yourself first: LeetCode 20 ↗. Then step through the solution below.
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 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.
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.
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
Now write it yourself on LeetCode 20 ↗, or go on: Reverse Linked List →
brackets has 8 brackets of three kinds. Does every bracket close, in the right order?partner maps each closing bracket to its opening one. stack starts empty: it will hold the open brackets, latest on top.ch takes the first bracket, the round (. It opens a pair: push it.[ opens another pair: push it on top.] closes a pair. The top is [, its partner: pop it.{ opens another pair: push it on top.( opens another pair: push it on top.) closes a pair. The top is (, its partner: pop it.} closes a pair. The top is {, its partner: pop it.) closes a pair. The top is (, its partner: pop it. The stack is empty again.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.
| Approach | Time | Space |
|---|---|---|
| Brute force: delete adjacent pairs until none is left | O(n2) | O(n) |
| Stack, one pass this page | O(n) | O(n) |
True.)(: the stack is empty at ), so the function returns False at once.(]: the top is (, but ] needs [, so the function returns False.((: 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).
The same code on the statement's ([)], where two pairs cross. Press → for each step.
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
brackets has 4 brackets of two kinds. Does every bracket close, in the right order?partner maps each closing bracket to its opening one. stack starts empty: it will hold the open brackets, latest on top.ch takes the first bracket, the round (. It opens a pair: push it.[ opens another pair: push it on top.) closes a pair, but the top is [, not its partner (: the answer is no.[ was opened last, so it must close first. One wrong closing bracket is enough.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.
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
Now write it yourself on LeetCode 20 ↗, or go on: Reverse Linked List →
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 stackWhat 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.
LeetCode is a trademark of LeetCode LLC. VisiGrab is not affiliated with LeetCode or with Blind; the problems are told in our own words, with our own examples.