SDE & MLE Prep

20. Valid Parentheses

Problem

s contains only the brackets ()[]{}. Decide whether it is valid: every opening bracket is closed by the same type of bracket, in the correct (properly nested) order.

Example: "()[]{}" → true; "(]" → false; "([)]" → false

Push expected closers; on a closer, it must match the top.

Complexity: O(n).

class Solution:
    def isValid(self, s: str) -> bool:
        pair = {")": "(", "]": "[", "}": "{"}
        st = []
        for ch in s:
            if ch in pair:
                if not st or st.pop() != pair[ch]:
                    return False
            else:
                st.append(ch)
        return not st