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.
1using System;
2using System.Text;
3using System.Collections.Generic;
4
5public class Solution {
6 public string MinRemoveToMakeValid(string s) {
7 Stack<int> stack = new Stack<int>();
8 StringBuilder sb = new StringBuilder(s);
9
10 for (int i = 0; i < sb.Length; i++) {
11 if (sb[i] == '(') stack.Push(i);
12 else if (sb[i] == ')') {
13 if (stack.Count == 0) {
14 sb[i] = '*';
15 } else {
16 stack.Pop();
17 }
18 }
19 }
20
21 while (stack.Count > 0) {
22 sb[stack.Pop()] = '*';
23 }
24
25 return sb.ToString().Replace("*", "");
26 }
27}
This C# solution uses a stack to manage unmatched parentheses and employs StringBuilder for mutating the original string, marking, and replacing invalid parentheses.
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.
The C implementation uses an integer stack to track the positions of parentheses. It marks invalid parentheses with a dot character and subsequently uses a secondary pass to construct the valid string.