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.
1#include <iostream>
2#include <string>
3#include <stack>
4using namespace std;
5
6string minRemoveToMakeValid(string s) {
7 stack<int> stack;
8 string result = s;
9
10 for (int i = 0; i < s.length(); ++i) {
11 if (s[i] == '(') stack.push(i);
12 else if (s[i] == ')') {
13 if (!stack.empty()) stack.pop();
14 else result[i] = '*';
15 }
16 }
17
18 while (!stack.empty()) {
19 result[stack.top()] = '*';
20 stack.pop();
21 }
22
23 result.erase(remove(result.begin(), result.end(), '*'), result.end());
24 return result;
25}
Using a stack to store indices of unmatched opening brackets, we traverse the string removing invalid closing and then opening brackets. Invalid indices are marked and removed to keep the string valid.
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.