Minimum Remove to Make Valid Parentheses
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #1249
s contains lowercase letters and parentheses. Remove the minimum number of parentheses so the result is valid (balanced), and return any such result.
Examples
text
"lee(t(c)o)de)" → "lee(t(c)o)de" (other minimal answers are also accepted)
"a)b(c)d" → "ab(c)d"
"))((" → ""The tests accept any valid answer with the minimum number of removals.
Hints
- A
)with no open(before it must be removed. - Any
(still unmatched at the end must be removed. - Track the indices of unmatched
(with a stack.
Approach
Scan left to right with a stack of indices of (. On ): if the stack is non-empty, pop (matched); otherwise mark this ) for removal. At the end, mark every index left on the stack. Rebuild the string, skipping the marked indices. This removes exactly the unmatched parentheses, which is the minimum. O(n).
Complexity
Time: O(n). Space: O(n).
Python solution
def minRemoveToMakeValid(s):
remove, st = set(), []
for i, ch in enumerate(s):
if ch == "(":
st.append(i)
elif ch == ")":
if st:
st.pop()
else:
remove.add(i)
remove.update(st)
return "".join(ch for i, ch in enumerate(s) if i not in remove)JavaScript solution
function minRemoveToMakeValid(s) {
const remove = new Set(), st = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') st.push(i);
else if (s[i] === ')') { if (st.length) st.pop(); else remove.add(i); }
}
st.forEach((i) => remove.add(i));
return [...s].filter((_, i) => !remove.has(i)).join('');
}