Minimum Remove to Make Valid Parentheses

Medium

Topics
StringStack

Given a string s of lowercase letters and the characters ( and ), remove the minimum number of parentheses so that the result is valid, and return it.

A string is valid when it is empty, or consists of letters only, or is a concatenation of valid strings, or is a valid string wrapped in one matching pair.

LeetCode notes that several answers may exist. That is true of which positions are removed — for "(()" either opening bracket can go — but both choices leave the same string, "()", and that is what is compared. So the answer here is unique and no tie-break is needed.

Example 1

sl0e1e2(3t4(5c6)7o8)9d10e11)12
answerlee(t(c)o)de
close bracket with nothing to match
A bracket has to go exactly when it cannot be matched, and the two directions fail differently: a close bracket is doomed the moment it appears with no open one waiting, while an open bracket is only doomed once the string ends. Here 1 bracket are unmatchable, leaving lee(t(c)o)de. Letters are never removed.
One cell per character; the small numbers underneath are indices.
Input:  s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: The final close bracket has nothing to match, so it goes. The other brackets already pair up.

Example 2

sa0)1b2(3c4)5d6
answerab(c)d
close bracket with nothing to match
Input:  s = "a)b(c)d"
Output: "ab(c)d"
Explanation: The close bracket at index 1 arrives before any open bracket.

Example 3

s)0)1(2(3
answer
empty string
close bracket with nothing to matchopen bracket never closed
Input:  s = "))(("
Output: ""
Explanation: Not one bracket can be matched, so all four are removed and only the empty string is left.

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is either a lowercase English letter, ( or )
Editorial — intuition, approach, complexity and pitfalls

Intuition

A bracket needs removing exactly when it cannot be matched, and the two directions fail for different reasons. A ) is doomed the moment it appears with no unmatched ( before it — nothing later can rescue it. A ( is only doomed once the string ends with no ) left to close it, which is not knowable until the end.

So the close brackets can be judged on the spot during a left-to-right scan, while the open brackets have to be held as candidates and judged afterwards. Whatever is still being held when the scan finishes is unmatched and goes.

Minimality follows because nothing is removed unless it is unmatchable, and an unmatchable bracket has to be removed in any valid result. The count is therefore forced, and so is the resulting string.

Approach

  1. Scan left to right, keeping the indices of unmatched ( on a stack and a set of indices to delete.
  2. On a (, push its index.
  3. On a ), pop a matching index if the stack has one; if it is empty, mark this index for deletion.
  4. When the scan ends, mark every index still on the stack for deletion — those opens were never closed.
  5. Rebuild the string, skipping the marked indices. Letters are never touched.

Walkthrough

s = "lee(t(c)o)de)"
      0123456789...

index char  action                        stack   delete
  3    (    push 3                        [3]
  5    (    push 5                        [3,5]
  7    )    pop 5, matched                [3]
  9    )    pop 3, matched                []
 12    )    stack empty -> delete 12      []      {12}

nothing left on the stack, so no opens to remove
result: drop index 12  ->  "lee(t(c)o)de"

---

s = "))(("
  0  )  empty -> delete 0
  1  )  empty -> delete 1
  2  (  push 2
  3  (  push 3
end: 2 and 3 never closed -> delete both
every character removed  ->  ""

Complexity

  • Time — O(n): one scan to decide and one to rebuild.
  • Space — O(n): the stack and the delete set, both at most one entry per character.

Common Pitfalls

  • Removing a ) on sight whenever the running balance is negative but forgetting the leftover ( at the end. "(a" needs its bracket removed too.
  • Counting unmatched brackets and then deleting that many from the wrong end. It matters which ones go — in example 2 the doomed bracket is at index 1, not the last one.
  • Removing letters. Only parentheses are ever deleted.
  • Rebuilding with repeated string concatenation inside the loop, which turns a linear scan quadratic in languages with immutable strings.

Full Solution — all languages

class Solution:
    def minRemoveToMakeValid(self, s):
        remove = set()
        stack = []
        for i, c in enumerate(s):
            if c == "(":
                stack.append(i)
            elif c == ")":
                if stack:
                    stack.pop()
                else:
                    remove.add(i)
        remove.update(stack)
        return "".join(c for i, c in enumerate(s) if i not in remove)
SensAI
Beta
Tap the mic to stop voice mode