KatInterview

301. Remove Invalid Parentheses

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all possible valid strings by removing the minimum number of parentheses from a given string. The string can also contain letters. A key challenge is that we need to find all solutions with the minimum number of removals, not just any valid string.

Solution

Remove Invalid Parentheses in Python

class Solution:
    def removeInvalidParentheses(self, s: str) -> List[str]:
        result = []
        
        def remove(s, last_i, last_j, par):
            stack = 0
            for i in range(last_i, len(s)):
                if s[i] == par[0]:
                    stack += 1
                elif s[i] == par[1]:
                    stack -= 1
                
                if stack >= 0:
                    continue
                
                # Found an invalid prefix, s[0...i]. We need to remove a par[1] from s[last_j...i].
                for j in range(last_j, i + 1):
                    # If s[j] is a parenthesis to remove, and it's the first one in a consecutive sequence.
                    if s[j] == par[1] and (j == last_j or s[j-1] != par[1]):
                        # Recurse with the character at j removed.
                        next_s = s[:j] + s[j+1:]
                        remove(next_s, i, j, par)
                # After trying all removal options, stop the current execution path.
                return

            # The string is valid from left to right.
            # Now check from right to left.
            reversed_s = s[::-1]

            if par[0] == '(':
                # This was the first pass (L->R).
                remove(reversed_s, 0, 0, (')', '('))
            else:
                # This was the second pass (R->L on original string).
                # The string is now fully validated.
                result.append(reversed_s)

        remove(s, 0, 0, ('(', ')'))
        return result

Remove Invalid Parentheses in Java

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        List<String> result = new ArrayList<>();
        remove(s, 0, 0, new char[]{'(', ')'}, result);
        return result;
    }

    private void remove(String s, int last_i, int last_j, char[] par, List<String> result) {
        int stack = 0;
        for (int i = last_i; i < s.length(); i++) {
            if (s.charAt(i) == par[0]) {
                stack++;
            }
            if (s.charAt(i) == par[1]) {
                stack--;
            }
            if (stack >= 0) {
                continue;
            }

            // Found an invalid prefix, s[0...i]. We need to remove a 'par[1]' from s[last_j...i].
            for (int j = last_j; j <= i; j++) {
                // If s.charAt(j) is a parenthesis to remove, and it's the first one in a consecutive sequence.
                if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) {
                    // Recurse with the character at j removed.
                    String next_s = s.substring(0, j) + s.substring(j + 1);
                    remove(next_s, i, j, par, result);
                }
            }
            // After trying all removal options for the found invalid prefix, stop the current execution path.
            return;
        }

        // The string is valid from left to right (no extra closing parens).
        // Now check from right to left for extra opening parens.
        String reversed_s = new StringBuilder(s).reverse().toString();

        if (par[0] == '(') { // This was the first pass (L->R).
            remove(reversed_s, 0, 0, new char[]{')', '('}, result);
        } else { // This was the second pass (R->L on the original string).
            // The string is now fully validated.
            result.add(reversed_s);
        }
    }
}

Remove Invalid Parentheses in C++

class Solution {
public:
    vector<string> removeInvalidParentheses(string s) {
        vector<string> result;
        remove(s, 0, 0, {'(', ')'}, result);
        return result;
    }

private:
    void remove(string s, int last_i, int last_j, const vector<char>& par, vector<string>& result) {
        int stack = 0;
        for (int i = last_i; i < s.length(); ++i) {
            if (s[i] == par[0]) stack++;
            if (s[i] == par[1]) stack--;
            if (stack >= 0) continue;

            // Found an invalid prefix, s[0...i]. We need to remove a 'par[1]' from s[last_j...i].
            for (int j = last_j; j <= i; ++j) {
                // If s[j] is a parenthesis to remove, and it's the first one in a consecutive sequence.
                if (s[j] == par[1] && (j == last_j || s[j - 1] != par[1])) {
                    // Recurse with the character at j removed.
                    string next_s = s.substr(0, j) + s.substr(j + 1);
                    remove(next_s, i, j, par, result);
                }
            }
            // After trying all removal options for the found invalid prefix, stop the current execution path.
            return;
        }

        // The string is valid from left to right (no extra closing parens).
        // Now check from right to left for extra opening parens.
        string reversed_s = s;
        reverse(reversed_s.begin(), reversed_s.end());

        if (par[0] == '(') { // This was the first pass (L->R).
            remove(reversed_s, 0, 0, {')', '('}, result);
        } else { // This was the second pass (R->L on the original string).
            // The string is now fully validated.
            result.push_back(reversed_s);
        }
    }
};

Remove Invalid Parentheses in TypeScript

function removeInvalidParentheses(s: string): string[] {
    const result: string[] = [];

    function remove(current_s: string, last_i: number, last_j: number, par: [string, string]) {
        let stack = 0;
        for (let i = last_i; i < current_s.length; i++) {
            if (current_s[i] === par[0]) {
                stack++;
            } else if (current_s[i] === par[1]) {
                stack--;
            }

            if (stack >= 0) {
                continue;
            }

            // Found an invalid prefix, current_s[0...i]. 
            // We need to remove a 'par[1]' from current_s[last_j...i].
            for (let j = last_j; j <= i; j++) {
                // If current_s[j] is a parenthesis to remove, and it's the first one
                // in a consecutive sequence.
                if (current_s[j] === par[1] && (j === last_j || current_s[j - 1] !== par[1])) {
                    // Recurse with the character at j removed.
                    const next_s = current_s.substring(0, j) + current_s.substring(j + 1);
                    remove(next_s, i, j, par);
                }
            }
            // After trying all removal options, stop the current execution path.
            return;
        }

        // The string is valid from left to right (no extra closing parens).
        // Now check from right to left for extra opening parens.
        const reversed_s = current_s.split('').reverse().join('');

        if (par[0] === '(') { // This was the first pass (L->R).
            remove(reversed_s, 0, 0, [')', '(']);
        } else { // This was the second pass (R->L on the original string).
            // The string is now fully validated.
            result.push(reversed_s);
        }
    }

    remove(s, 0, 0, ['(', ')']);
    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.