What is Valid Parentheses
A string of brackets is valid when every opener is closed by the matching closer, in the right order.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each bracket is pushed and popped at most once. |
| Space | O(n) | A run of openers fills the stack. |
Implementation
pairs = {')':'(', ']':'[', '}':'{'}
def solve(self, s):
st = []
for ch in s:
if ch in '([{':
st.append(ch)
elif not st or st.pop() != pairs.get(ch):
return 0
return 1 if not st else 0