AlgoInsight

DSA problem

Minimum Remove to Make Valid Parentheses

MediumStacksPattern: Stackstop600MetaAmazonMicrosoftGoogleBloomberg

Given a string s of '(', ')' and lowercase English characters, your task is to remove the minimum number of parentheses ('(' or ')', in any positions) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if it is the empty string, contains only lowercase characters, or can be written as AB (A concatenated with B), where A and B are valid strings, or it can be written as (A), where A is a valid string.

A two-pass O(n) approach (count opens and closes) works but is awkward to reason about. The cleanest formulation is the stack approach: scan the string keeping a stack of indices of unmatched '(' characters. When you see a ')', if the stack has an unmatched '(', pop it (a valid pair is formed); if it does not, mark this ')' as a "to remove" position.

After the scan, any indices left in the stack are unmatched '(' that must also be removed. Collect all such indices into a set, then rebuild the string by emitting every character whose index is not marked. This is O(n) time and O(n) extra space, and naturally produces one valid answer with the minimum number of removals.

Examples

Example 1
Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: Removing the trailing unmatched ')' makes the string valid. Any single removal that achieves validity is acceptable.
Example 2
Input: s = "a)b(c)d"
Output: "ab(c)d"
Explanation: Remove the unmatched ')' after 'a'.
Example 3
Input: s = "))(("
Output: ""
Explanation: No valid pairing exists; every parenthesis must be removed.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stackstringmatching

Browse all DSA problems