Minimum Remove To Make Valid Parentheses

5 min read

Parentheses are everywhere in programming, from mathematical expressions to function calls in source code. The task is simple to state but requires careful thinking: given a string made of letters and parentheses, remove the minimum number of '(' or ')' characters so that the remaining string is valid. Because of that, when a string contains mismatched or unbalanced parentheses, it can break syntax and cause runtime errors. A valid string means every opening parenthesis has a corresponding closing parenthesis in the correct order. This is exactly where the minimum remove to make valid parentheses challenge comes in. Whether you are preparing for a technical interview or practicing algorithmic problem-solving, mastering this problem strengthens your understanding of string manipulation and stack-based logic.

What Is the Minimum Remove to Make Valid Parentheses Problem?

The minimum remove to make valid parentheses problem is a classic string-processing challenge often found on coding platforms such as LeetCode (problem 1249). You are given a string s that contains lowercase English letters and parentheses characters '(' and ')'. Here's the thing — your goal is to return a valid string by removing the fewest number of parentheses possible. If there are multiple valid results, you can return any one of them.

For example:

  • Input: "lee(t(c)o)de)"

  • Output: "lee(t(c)o)de" or "lee(t(c)ode)"

  • Input: "a)b(c)d"

  • Output: "ab(c)d"

  • Input: "))(("

  • Output: ""

Notice that the problem does not ask you to rearrange characters. Think about it: you are only allowed to delete parentheses. Letters must remain untouched and in their original positions Still holds up..

What Makes Parentheses Valid?

Before solving

Before solving, it helps to formalize the rules that define a valid parentheses string. A string is considered valid if and only if:

  1. Every opening parenthesis '(' has a corresponding closing parenthesis ')' later in the string.
  2. Every closing parenthesis ')' has a corresponding opening parenthesis '(' earlier in the string.
  3. Pairs are properly nested. You cannot close a parenthesis that wasn't the most recently opened unclosed one (e.g., )( or (() are invalid).

Essentially, as you scan the string from left to right, the count of closing parentheses should never exceed the count of opening parentheses at any point, and the total counts must be equal by the end Simple as that..

Approach 1: Stack-Based Index Tracking

The most intuitive approach uses a stack to track the indices of opening parentheses. Since we cannot modify the string in place efficiently (strings are immutable in many languages), we mark indices for removal.

Algorithm:

  1. Initialize an empty stack to store indices of '('.
  2. Initialize a Set (or boolean array) toRemove to store indices of parentheses to delete.
  3. Iterate through the string with index i:
    • If s[i] == '(': Push i onto the stack.
    • If s[i] == ')':
      • If the stack is not empty: Pop the top index (matching pair found).
      • If the stack is empty: Add i to toRemove (unmatched closing bracket).
  4. After the loop, any indices remaining in the stack represent unmatched opening parentheses. Add all of them to toRemove.
  5. Build the result string by iterating through s again and appending characters whose indices are not in toRemove.

Why this works: The stack enforces the Last-In-First-Out (LIFO) property required for valid nesting. Unmatched closers are caught immediately because there is no opener on the stack to pair with. Unmatched openers are left in the stack at the end.

Complexity:

  • Time: O(N) — We traverse the string twice.
  • Space: O(N) — Stack and Set can grow up to size N in the worst case (e.g., ((((().

Approach 2: Two-Pass Constant Space (Excluding Output)

We can optimize space to O(1) auxiliary space (ignoring the output string builder) by using two linear passes without a stack. We track a balance counter instead Not complicated — just consistent. Worth knowing..

Algorithm:

  1. First Pass (Left-to-Right): Remove invalid ')'.
    • Initialize balance = 0 and a StringBuilder (or list) sb.
    • Iterate through s:
      • If char is '(': balance++, append to sb.
      • If char is ')':
        • If balance == 0: Skip this char (invalid closer).
        • Else: balance--, append to sb.
      • If char is a letter: Append to sb.
    • At this stage, sb has no invalid ')', but may have extra '(' (indicated by balance > 0).
  2. Second Pass (Right-to-Left): Remove excess '('.
    • Initialize result builder.
    • Iterate sb backwards:
      • If char is '(' and balance > 0: balance--, skip this char (remove excess opener).
      • Else: Prepend char to result (or append to a new builder and reverse at the end).
  3. Return result.

Why this works: The first pass ensures no prefix has more closers than openers. The balance at the end of pass one equals the number of unmatched openers. The second pass removes exactly that many openers from the right side, preserving the leftmost openers which are more likely to have valid matches.

Complexity:

  • Time: O(N) — Two passes.
  • Space: O(N) for the output builder, but O(1) auxiliary space (just integer counters).

Edge Cases to Consider

  • Empty String: Returns empty string.
  • No Parentheses: Returns original string (e.g., "abc").
  • All Invalid: " ))(( " returns "".
  • Nested Valid: "(a(b)c)" returns same string.
  • Letters Interspersed: Logic must strictly ignore letters during balance checks but preserve them in output.

Practical Implementation Tips

  • Language Specifics: In Python, use a list as a stack and a set for removal indices; join a list comprehension for the final string. In Java, use Deque<Integer> and StringBuilder. In C++, use vector<int> as stack and string builder.
  • Mutability: If the language allows mutable strings (like C++ std::string or Rust String), you can mark characters with a placeholder (e.g., *) during the first pass and erase them in a second pass, avoiding a
What's New

New Writing

Curated Picks

While You're Here

Thank you for reading about Minimum Remove To Make Valid Parentheses. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home