SDE & MLE Prep

32. Longest Valid Parentheses

Problem

s contains only ( and ). Return the length of its longest valid (well-formed) parentheses substring.

Example: "(()" → 2; ")()())" → 4

Constraints: length ≤ 3·10⁴.

Stack of indices, seeded with -1 as the "last invalid position". ( → push index. ) → pop; if the stack is empty, push this index as the new base; else the valid run length is i − stack[-1].

s = ) ( ) ( ) )
i   0 1 2 3 4 5
i=0 ')' pop -1 -> empty -> push 0
i=2 ')' pop 1  -> len 2-0 = 2
i=4 ')' pop 3  -> len 4-0 = 4   <- best

Complexity: O(n).

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        st, best = [-1], 0
        for i, ch in enumerate(s):
            if ch == "(":
                st.append(i)
            else:
                st.pop()
                if not st:
                    st.append(i)
                else:
                    best = max(best, i - st[-1])
        return best