Simple Solution with Diagrams in Video - JavaScript, C++, Java, Python
VideoPlease upvote here so others save time too!Like the video on YouTube if you found it usefulClick here to subscribe on YouTube:
https://www.youtube.com/@may
# Video
Please upvote here so others save time too!

Like the video on YouTube if you found it useful

Click here to subscribe on YouTube:
https://www.youtube.com/@mayowadan?sub_confirmation=1

Thanks!

https://youtu.be/Lruz_Tp4DtQ?si=2R9QottyEFRi8XSd

```Javascript []
/**
 * @param {string} s
 * @return {string}
 */
var minRemoveToMakeValid = function (s) {

    let stack = [];
    let s_list = Array.from(s);

    for (let i = 0; i < s.length; i++) {
        let val = s[i];

        // if stack is not empty and top element of stack is an opening parenthesis
        // and the current element is a closing parenthesis
        if (stack.length > 0 && stack[stack.length - 1][0] === '(' && val === ')') {

            // pop the opening parenthesis as it makes a valid pair
            // with the current closing parenthesis
            stack.pop();
        }
        // if the current value is an opening or a closing parenthesis
        else if (val === '(' || val === ')') {

            // push onto stack
            stack.push([val, i]);
        }
    }

    // Remove the invalid parentheses
    for (let p of stack) {
        s_list[p[1]] = "";
    }

    // convert the list to string
    let result = s_list.join('');
    return result;
};
```
```Python []
class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        stack = []
        to_remove = set()

        # First pass: Identify the positions of invalid parentheses
        for i, char in enumerate(s):
            if char == "(":
                stack.append(i)
            elif char == ")":
                if stack:
                    stack.pop()
                else:
                    to_remove.add(i)

        # Add remaining unmatched '(' positions to the set
        while stack:
            to_remove.add(stack.pop())

        # Build the result string by skipping invalid parentheses
        result = []
        for i, char in enumerate(s):
            if i not in to_remove:
                result.append(char)

        return "".join(result)

```
```Java []
class Solution {
    public String minRemoveToMakeValid(String s) {
        Stack<Integer> stack = new Stack<>();
        Set<Integer> toRemove = new HashSet<>();

        // First pass: Identify the positions of invalid parentheses
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(i);
            } else if (c == ')') {
                if (!stack.isEmpty() && s.charAt(stack.peek()) == '(') {
                    stack.pop();
                } else {
                    toRemove.add(i);
                }
            }
        }

        // Add remaining unmatched '(' positions to the set
        while (!stack.isEmpty()) {
            toRemove.add(stack.pop());
        }

        // Build the result string by skipping invalid parentheses
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (!toRemove.contains(i)) {
                result.append(s.charAt(i));
            }
        }

        return result.toString();
    }
}

```
```C++ []
class Solution {
public:
    string minRemoveToMakeValid(string s) {
        stack<int> stk;
        vector<bool> toRemove(s.size(), false);

        // First pass: Identify the positions of invalid parentheses
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(') {
                stk.push(i);
            } else if (s[i] == ')') {
                if (!stk.empty() && s[stk.top()] == '(') {
                    stk.pop();
                } else {
                    toRemove[i] = true;
                }
            }
        }

        // Mark remaining unmatched '(' as invalid
        while (!stk.empty()) {
            toRemove[stk.top()] = true;
            stk.pop();
        }

        // Build the result string by skipping invalid parentheses
        string result;
        for (int i = 0; i < s.size(); ++i) {
            if (!toRemove[i]) {
                result += s[i];
            }
        }

        return result;
    }
};

```
['Python', 'C++', 'Java', 'Python3', 'JavaScript']