KatInterview

241. Different Ways to Add 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 requires us to compute all possible results from a string expression containing numbers and operators (+, -, *). The ambiguity in the result comes from the different ways we can group the numbers and operators using parentheses. This essentially means we need to explore all possible orders of operations.

Solution

Different Ways to Add Parentheses in Python

class Solution:
    def diffWaysToCompute(self, expression: str) -> List[int]:
        # Using a dictionary for memoization.
        memo = {}

        def compute(expr: str) -> List[int]:
            # If result for expr is already computed, return it.
            if expr in memo:
                return memo[expr]

            # If the expression is just a number, convert and return.
            if expr.isdigit():
                memo[expr] = [int(expr)]
                return [int(expr)]
            
            results = []
            for i, char in enumerate(expr):
                if char in "+-*":
                    # If character is an operator, split and recurse.
                    left_parts = compute(expr[:i])
                    right_parts = compute(expr[i+1:])
                    
                    # Combine results from left and right parts.
                    for l in left_parts:
                        for r in right_parts:
                            if char == '+':
                                results.append(l + r)
                            elif char == '-':
                                results.append(l - r)
                            else: # '*'
                                results.append(l * r)
            
            # Store results in memo and return.
            memo[expr] = results
            return results

        return compute(expression)

Different Ways to Add Parentheses in Java

class Solution {
    // Memoization table to store results for computed expressions.
    private Map<String, List<Integer>> memo = new HashMap<>();

    public List<Integer> diffWaysToCompute(String expression) {
        // If the result for this expression is already computed, return it.
        if (memo.containsKey(expression)) {
            return memo.get(expression);
        }

        List<Integer> results = new ArrayList<>();
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (c == '+' || c == '-' || c == '*') {
                // If character is an operator, split the string into two parts
                // and recursively compute the results for each part.
                String leftPart = expression.substring(0, i);
                String rightPart = expression.substring(i + 1);
                
                List<Integer> leftResults = diffWaysToCompute(leftPart);
                List<Integer> rightResults = diffWaysToCompute(rightPart);

                // Combine the results from the left and right parts.
                for (int l : leftResults) {
                    for (int r : rightResults) {
                        if (c == '+') {
                            results.add(l + r);
                        } else if (c == '-') {
                            results.add(l - r);
                        } else { // '*'
                            results.add(l * r);
                        }
                    }
                }
            }
        }

        // Base case: If no operators are found, the expression is a single number.
        if (results.isEmpty()) {
            results.add(Integer.parseInt(expression));
        }

        // Store the computed results in the memo table and return them.
        memo.put(expression, results);
        return results;
    }
}

Different Ways to Add Parentheses in C++

class Solution {
public:
    // Memoization table to store results for computed expressions.
    unordered_map<string, vector<int>> memo;

    vector<int> diffWaysToCompute(string expression) {
        // If the result for this expression is already computed, return it.
        if (memo.count(expression)) {
            return memo[expression];
        }

        vector<int> results;
        for (int i = 0; i < expression.length(); ++i) {
            char c = expression[i];
            if (c == '+' || c == '-' || c == '*') {
                // If character is an operator, split the string into two parts
                // and recursively compute the results for each part.
                string leftPart = expression.substr(0, i);
                string rightPart = expression.substr(i + 1);
                
                vector<int> leftResults = diffWaysToCompute(leftPart);
                vector<int> rightResults = diffWaysToCompute(rightPart);

                // Combine the results from the left and right parts.
                for (int l : leftResults) {
                    for (int r : rightResults) {
                        if (c == '+') {
                            results.push_back(l + r);
                        } else if (c == '-') {
                            results.push_back(l - r);
                        } else { // '*'
                            results.push_back(l * r);
                        }
                    }
                }
            }
        }

        // Base case: If no operators are found, the expression is a single number.
        if (results.empty()) {
            results.push_back(stoi(expression));
        }

        // Store the computed results in the memo table and return them.
        return memo[expression] = results;
    }
};

Different Ways to Add Parentheses in TypeScript

function diffWaysToCompute(expression: string): number[] {
    // Memoization map. Using a closure to maintain state.
    const memo = new Map<string, number[]>();

    function compute(expr: string): number[] {
        // If the result for this expression is already computed, return it.
        if (memo.has(expr)) {
            return memo.get(expr)!;
        }

        const results: number[] = [];
        let isNumber = true;
        for (let i = 0; i < expr.length; i++) {
            const char = expr[i];
            if (char === '+' || char === '-' || char === '*') {
                isNumber = false; // Found an operator
                // Split the string into two parts and recursively compute.
                const leftParts = compute(expr.substring(0, i));
                const rightParts = compute(expr.substring(i + 1));

                // Combine results from the left and right parts.
                for (const l of leftParts) {
                    for (const r of rightParts) {
                        if (char === '+') {
                            results.push(l + r);
                        } else if (char === '-') {
                            results.push(l - r);
                        } else { // '*'
                            results.push(l * r);
                        }
                    }
                }
            }
        }

        // Base case: If no operators were found, the expression is a single number.
        if (isNumber) {
            results.push(parseInt(expr, 10));
        }

        // Store the computed results in the memo map and return them.
        memo.set(expr, results);
        return results;
    }
    
    return compute(expression);
};

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.