KatInterview

22. Generate Parentheses

MediumSolutions 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 generate all possible valid combinations of n pairs of parentheses. A combination is considered "well-formed" or "valid" if two conditions are met:

Solution

Generate Parentheses in Python

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        result = []

        # Helper function for backtracking
        # current_string: the string being built
        # open_count: number of open parentheses used
        # close_count: number of close parentheses used
        def backtrack(current_string, open_count, close_count):
            # Base case: if the string has reached the desired length (2*n)
            if len(current_string) == 2 * n:
                result.append(current_string)
                return

            # Condition 1: Can add an opening parenthesis if we haven't used all n of them.
            if open_count < n:
                backtrack(current_string + "(", open_count + 1, close_count)
            
            # Condition 2: Can add a closing parenthesis if the number of closing
            # parentheses is less than the number of opening ones.
            if close_count < open_count:
                backtrack(current_string + ")", open_count, close_count + 1)

        # Start the backtracking process with an empty string and zero counts.
        backtrack("", 0, 0)
        return result

Generate Parentheses in Java

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        // Start the backtracking process with an empty StringBuilder.
        backtrack(result, new StringBuilder(), 0, 0, n);
        return result;
    }

    // Helper function to generate parentheses using backtracking.
    // result: stores all valid combinations.
    // current: a mutable string builder for efficient string construction.
    // open: number of open parentheses used.
    // close: number of close parentheses used.
    // n: total number of pairs of parentheses.
    private void backtrack(List<String> result, StringBuilder current, int open, int close, int n) {
        // Base case: if the string has reached the desired length (2*n).
        if (current.length() == n * 2) {
            result.add(current.toString());
            return;
        }

        // Condition 1: We can add an opening parenthesis if we haven't used all n of them.
        if (open < n) {
            current.append("(");
            // Recurse with an added opening parenthesis.
            backtrack(result, current, open + 1, close, n);
            // Backtrack: remove the character we just added to explore other possibilities.
            current.deleteCharAt(current.length() - 1);
        }

        // Condition 2: We can add a closing parenthesis if it's balanced.
        // i.e., the count of closing parentheses is less than the count of opening ones.
        if (close < open) {
            current.append(")");
            // Recurse with an added closing parenthesis.
            backtrack(result, current, open, close + 1, n);
            // Backtrack: remove the character we just added.
            current.deleteCharAt(current.length() - 1);
        }
    }
}

Generate Parentheses in C++

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        // Start the backtracking process with an empty string and initial counts.
        backtrack(result, "", 0, 0, n);
        return result;
    }

private:
    // Helper function to generate parentheses using backtracking.
    // result: stores all valid combinations.
    // current_string: the string being built.
    // open: number of open parentheses used.
    // close: number of close parentheses used.
    // n: total number of pairs of parentheses.
    void backtrack(vector<string>& result, string current_string, int open, int close, int n) {
        // Base case: if the string has reached the desired length (2*n).
        if (current_string.length() == n * 2) {
            result.push_back(current_string);
            return;
        }

        // Condition 1: We can add an opening parenthesis if we haven't used all n of them.
        if (open < n) {
            // Recurse with an added opening parenthesis.
            backtrack(result, current_string + "(", open + 1, close, n);
        }

        // Condition 2: We can add a closing parenthesis if it's balanced.
        // i.e., the count of closing parentheses is less than the count of opening ones.
        if (close < open) {
            // Recurse with an added closing parenthesis.
            backtrack(result, current_string + ")", open, close + 1, n);
        }
    }
};

Generate Parentheses in TypeScript

function generateParenthesis(n: number): string[] {
    const result: string[] = [];

    // Helper function for backtracking.
    // currentString: the string being built.
    // openCount: number of open parentheses used.
    // closeCount: number of close parentheses used.
    const backtrack = (currentString: string, openCount: number, closeCount: number) => {
        // Base case: if the string has reached the desired length (2*n).
        if (currentString.length === 2 * n) {
            result.push(currentString);
            return;
        }

        // Condition 1: We can add an opening parenthesis if we haven't used all n of them.
        if (openCount < n) {
            // Recurse with an added opening parenthesis.
            backtrack(currentString + '(', openCount + 1, closeCount);
        }

        // Condition 2: We can add a closing parenthesis if it's balanced.
        // i.e., the count of closing parentheses is less than the count of opening ones.
        if (closeCount < openCount) {
            // Recurse with an added closing parenthesis.
            backtrack(currentString + ')', openCount, closeCount + 1);
        }
    };

    // Start the backtracking process with an empty string and zero counts.
    backtrack('', 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.