Given a string s
consisting 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:
AB
(A
concatenated with B
), where A
and B
are valid strings, or(A)
, where A
is a valid string.For example:
s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
(or "lee(t(co)de)"
or "lee(t(c)ode)"
) would also be accepted.s = "a)b(c)d"
Output: "ab(c)d"
s = "))(("
Output: ""
Write an algorithm to solve this problem efficiently. Explain the time and space complexity of your solution. Also, what are some edge cases you considered in your solution?
The most straightforward approach is to generate all possible subsequences of the given string by either keeping or removing each parenthesis. Then, check if each subsequence is a valid parentheses string. We keep the valid string of maximal length. If several valid strings have the same maximal length, any of them can be returned.
This approach is highly inefficient due to the exponential number of possible subsequences (2^n, where n is the length of the string).
A more efficient approach involves using a stack (or a counter) to keep track of open parentheses. We iterate through the string, and for each character, we perform the following:
After the first iteration, we will know which closing parentheses to remove. However, we might still have unmatched opening parentheses in the stack (or a counter value that's not zero). In a second iteration, we eliminate the extra opening parentheses from our constructed string.
Edge Cases
Code (Python)
def min_remove_to_make_valid(s: str) -> str:
stack = []
indices_to_remove = set()
for i, char in enumerate(s):
if char == '(':
stack.append(i)
elif char == ')':
if stack:
stack.pop()
else:
indices_to_remove.add(i)
while stack:
indices_to_remove.add(stack.pop())
result = ""
for i, char in enumerate(s):
if i not in indices_to_remove:
result += char
return result