Sponsored
Sponsored
This approach involves performing two passes over the string. In the first pass, traverse the string to identify unmatched closing parentheses and their indices. In the second pass, traverse from right to left to identify unmatched opening parentheses. This process allows removing these indices to yield a balanced parentheses string.
Time Complexity: O(n), where n is the length of the string, since each character is visited once in each pass.
Space Complexity: O(n), as we potentially have to store the valid portion of the string.
1def minRemoveToMakeValid(s: str) -> str:
2 stack = []
3 s = list(s)
4
5 for i, char in enumerate(s):
6 if char == '(':
7 stack.append(i)
8 elif char == ')':
9 if stack:
10 stack.pop()
11 else:
12 s[i] = ''
13
14 for i in stack:
15 s[i] = ''
16
17 return ''.join(s)
This method uses list mutation to mark invalid parentheses with empty strings. A stack is used to keep track of unmatched opening brackets.
This strategy employs a single-pass solution with a stack to track the indices of unmatched parentheses. Upon completing the pass, these tracked indices inform which characters can remain in the final valid string output. This approach saves memory by avoiding additional passes over the string.
Time Complexity: O(n), since each position in the strings is evaluated at most twice.
Space Complexity: O(n) for the indices stored during parentheses checking.
Leveraging JavaScript's flexible array management, the method capitalizes on character marking features modelled after stack behavior assurance.