← Stacks & Queues

Drill #21 — Valid parentheses string

Easy Index Stack Stacks & Queues

In plain English: Check if a string of parentheses is properly opened and closed.

Every open paren expects exactly one close paren — the stack tracks unmatched opens and must be empty at the end.

Prompt

Check if a string of parentheses () is valid.

Try to write it from scratch before scrolling down.

Solution

def is_valid(s):
    stack = []  # track unmatched open parens
    for c in s:
        if c == '(':
            stack.append(c)
        elif c == ')':
            if not stack:
                return False  # no matching open
            stack.pop()
    return len(stack) == 0  # all opens must be matched

# Test: is_valid("(())()") == True
# Test: is_valid("(()") == False
O(n) time · O(n) space

Related Micro Drills

← Drill #20 Drill #22 →