Minimum Remove to Make Valid Parentheses Problem
Description
LeetCode Problem 1249.
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
- It can be written as
AB(Aconcatenated withB), whereAandBare valid strings, or - It can be written as
(A), whereAis a valid string.
Example 1:
Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
Example 2:
Input: s = "a)b(c)d"
Output: "ab(c)d"
Example 3:
Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.
Constraints:
1 <= s.length <= 10^5s[i]is either'(',')', or lowercase English letter.
Solution
Approach: Two Passes
A string of parentheses is valid when, reading left to right, the number of open ( never goes negative and ends at zero. Letters play no part, so we keep all of them and only decide which parentheses to drop. Two kinds of parentheses must go:
- a
)that shows up when no(is open has nothing to close, so it can never be matched; - a
(that is still open at the end has no)after it to close it.
Pass 1, left to right. Keep a count openCount of unmatched (. Add one for each (. For a ), drop it if openCount is 0, otherwise keep it and subtract one. After this pass no prefix of the kept string has more ) than (.
Pass 2, right to left. openCount is now the number of ( left unmatched. Walk the kept characters backwards and drop the first openCount ( we see, that is, the last ones in the string. Dropping the rightmost opens is the key point: every ) that stayed after pass 1 was matched by an earlier (, and removing the latest opens never takes away one of those matches. Removing an earlier ( could leave a ) after it with nothing to close.
Each removal fixes exactly one parenthesis that could never be matched, so the count is the minimum. For "lee(t(c)o)de)" pass 1 drops the last ), and pass 2 has nothing left to drop.
Complexity: O(n) time and O(n) space for the kept characters, where n is the length of s.
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
# Pass 1, left to right: drop every ')' that has no open '(' to close.
kept = []
open_count = 0
for c in s:
if c == "(":
open_count += 1
elif c == ")":
if open_count == 0:
continue
open_count -= 1
kept.append(c)
# Pass 2, right to left: open_count '(' are still unmatched; drop the last ones.
out = []
for c in reversed(kept):
if c == "(" and open_count > 0:
open_count -= 1
continue
out.append(c)
return "".join(reversed(out))