mediumStringStackStack

Minimum Remove to Make Valid Parentheses

mediumTime: O(n)Space: O(n)

Signals to notice

remove minimum parentheses to make string validtrack excess opens and closesmark indices for removal

Brute force first

Try removing every subset and check validity. Exponential. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Stack of indices: push '(' indices. On ')': if stack has '(', pop (matched). Else mark this ')' for removal. After processing, remaining '(' on stack are also removed. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

The stack tracks unmatched '(' indices. Unmatched ')' are detected immediately. At the end, both types of unmatched parentheses are removed. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Only removing unmatched ')' — you must also remove unmatched '(' that remain on the stack after processing the entire string. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Stack Pattern