SDE & MLE Prep

1249. Minimum Remove to Make Valid Parentheses

Problem

Remove the fewest parentheses from s (letters plus ( and )) so the parentheses become valid, and return any valid result.

Example: "lee(t(c)o)de)" → "lee(t(c)o)de"; "))((" → ""

Constraints: length ≤ 10⁵.

Stack the indices of unmatched (; a ) with an empty stack is invalid. Afterwards, every index still on the stack is an invalid (. Remove all invalid indices.

Complexity: O(n).

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        st, bad = [], set()
        for i, ch in enumerate(s):
            if ch == "(":
                st.append(i)
            elif ch == ")":
                if st:
                    st.pop()
                else:
                    bad.add(i)
        bad.update(st)
        return "".join(ch for i, ch in enumerate(s) if i not in bad)