StackEasy

Valid Parentheses Visualizer

What is Valid Parentheses

A string of brackets is valid when every opener is closed by the matching closer, in the right order.

Approach

Scan once. The latest unmatched opener has to be the next one that closes. That is why a stack fits.

Visualization & algorithm

Openers on the stack
for each bracket:
if it opens: push it
else if the stack is empty: fail
else if the top mismatches: fail
else: pop
return 1 only if the stack is empty
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each bracket is pushed and popped at most once.
SpaceO(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