Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 6, 2024 17:18
Show Gist options
  • Save tatsuyax25/3ca8bced98f341bcbc5b8b647d2173ad to your computer and use it in GitHub Desktop.
Save tatsuyax25/3ca8bced98f341bcbc5b8b647d2173ad to your computer and use it in GitHub Desktop.
var minRemoveToMakeValid = function(s) {
// Convert the string to an array to facilitate removal of characters
let chars = s.split('');
// Stack to keep track of indices of opening parentheses
let stack = [];
// Iterate through the characters of the string
for (let i = 0; i < chars.length; i++) {
// If the character is an opening parenthesis, add its index to the stack
if (chars[i] === '(') {
stack.push(i);
}
// If the character is a closing parenthesis
else if (chars[i] === ')') {
// If stack is not empty and the top of the stack corresponds to an opening parenthesis,
// remove the opening parenthesis index from the stack
// Otherwise, mark the closing parenthesis for removal by replacing it with an empty string
if (stack.length !== 0) {
stack.pop();
} else {
chars[i] = '';
}
}
}
// Mark the remaining opening parentheses indices in the stack for removal
while (stack.length !== 0) {
chars[stack.pop()] = '';
}
// Join the characters array back into a string and return
return chars.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment