KatInterview

282. Expression Add Operators

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

Method: Backtracking (Depth-First Search)

This problem asks for all possible valid expressions, which strongly suggests a backtracking or Depth-First Search (DFS) approach. We need to explore all ways to partition the num string and place operators (+, -, *) in between.

Solution

Expression Add Operators in Python

class Solution:
    def addOperators(self, num: str, target: int) -> List[str]:
        result = []
        
        def backtrack(index: int, path: str, current_eval: int, last_operand: int):
            # Base case: if we have processed all digits
            if index == len(num):
                if current_eval == target:
                    result.append(path)
                return

            # Recursive step: iterate through all possible operands starting at index
            for i in range(index, len(num)):
                current_s = num[index:i+1]

                # Edge case: operands with more than one digit cannot start with '0'
                if len(current_s) > 1 and current_s[0] == '0':
                    break # Prune search space
                
                current_num = int(current_s)

                # If it's the first number, just append it without an operator
                if index == 0:
                    backtrack(i + 1, current_s, current_num, current_num)
                else:
                    # Try adding '+' operator
                    backtrack(i + 1, f"{path}+{current_s}", current_eval + current_num, current_num)
                    
                    # Try adding '-' operator
                    backtrack(i + 1, f"{path}-{current_s}", current_eval - current_num, -current_num)
                    
                    # Try adding '*' operator
                    # The new evaluation is (current_eval - last_operand) + (last_operand * current_num)
                    backtrack(i + 1, f"{path}*{current_s}", (current_eval - last_operand) + (last_operand * current_num), last_operand * current_num)

        if not num:
            return []
        
        backtrack(0, "", 0, 0)
        return result

Expression Add Operators in Java

class Solution {
    private List<String> result;
    private String num;
    private int target;

    public List<String> addOperators(String num, int target) {
        this.result = new ArrayList<>();
        if (num == null || num.length() == 0) {
            return result;
        }
        this.num = num;
        this.target = target;
        backtrack(0, new StringBuilder(), 0, 0);
        return result;
    }

    private void backtrack(int index, StringBuilder path, long currentEval, long lastOperand) {
        // Base case: if we have processed all digits
        if (index == num.length()) {
            if (currentEval == target) {
                result.add(path.toString());
            }
            return;
        }

        // Recursive step: iterate through all possible operands starting at index
        for (int i = index; i < num.length(); i++) {
            String currentStr = num.substring(index, i + 1);

            // Edge case: operands with more than one digit cannot start with '0'
            if (currentStr.length() > 1 && currentStr.charAt(0) == '0') {
                break; // Prune the search space
            }

            long currentNum = Long.parseLong(currentStr);
            int pathLen = path.length();

            // If it's the first number, just append it without an operator
            if (index == 0) {
                path.append(currentStr);
                backtrack(i + 1, path, currentNum, currentNum);
                path.setLength(pathLen); // Backtrack
            } else {
                // Try adding '+' operator
                path.append('+').append(currentStr);
                backtrack(i + 1, path, currentEval + currentNum, currentNum);
                path.setLength(pathLen); // Backtrack

                // Try adding '-' operator
                path.append('-').append(currentStr);
                backtrack(i + 1, path, currentEval - currentNum, -currentNum);
                path.setLength(pathLen); // Backtrack

                // Try adding '*' operator
                path.append('*').append(currentStr);
                backtrack(i + 1, path, (currentEval - lastOperand) + (lastOperand * currentNum), lastOperand * currentNum);
                path.setLength(pathLen); // Backtrack
            }
        }
    }
}

Expression Add Operators in C++

class Solution {
public:
    vector<string> addOperators(string num, int target) {
        vector<string> result;
        if (num.empty()) {
            return result;
        }
        backtrack(0, "", 0, 0, num, target, result);
        return result;
    }

private:
    void backtrack(int index, const string& path, long currentEval, long lastOperand, 
                   const string& num, int target, vector<string>& result) {
        // Base case: if we have processed all digits
        if (index == num.length()) {
            if (currentEval == target) {
                result.push_back(path);
            }
            return;
        }

        // Recursive step: iterate through all possible operands starting at index
        for (int i = index; i < num.length(); ++i) {
            string currentStr = num.substr(index, i - index + 1);

            // Edge case: operands with more than one digit cannot start with '0'
            if (currentStr.length() > 1 && currentStr[0] == '0') {
                break; // All subsequent numbers starting at this index will also have a leading zero
            }

            long currentNum = stol(currentStr);

            // If it's the first number, just append it without an operator
            if (index == 0) {
                backtrack(i + 1, currentStr, currentNum, currentNum, num, target, result);
            } else {
                // Try adding '+' operator
                backtrack(i + 1, path + "+" + currentStr, currentEval + currentNum, currentNum, num, target, result);

                // Try adding '-' operator
                backtrack(i + 1, path + "-" + currentStr, currentEval - currentNum, -currentNum, num, target, result);

                // Try adding '*' operator
                // The new evaluation is (currentEval - lastOperand) + (lastOperand * currentNum)
                backtrack(i + 1, path + "*" + currentStr, (currentEval - lastOperand) + (lastOperand * currentNum), lastOperand * currentNum, num, target, result);
            }
        }
    }
};

Expression Add Operators in TypeScript

function addOperators(num: string, target: number): string[] {
    const result: string[] = [];
    
    if (!num || num.length === 0) {
        return result;
    }

    function backtrack(index: number, path: string, currentEval: number, lastOperand: number): void {
        // Base case: if we have processed all digits
        if (index === num.length) {
            if (currentEval === target) {
                result.push(path);
            }
            return;
        }

        // Recursive step: iterate through all possible operands starting at index
        for (let i = index; i < num.length; i++) {
            const currentStr = num.substring(index, i + 1);

            // Edge case: operands with more than one digit cannot start with '0'
            if (currentStr.length > 1 && currentStr[0] === '0') {
                break; // Prune the search space
            }

            // JavaScript's 'number' is a 64-bit float, sufficient for up to 15-17 decimal digits.
            const currentNum = Number(currentStr);

            // If it's the first number, just append it without an operator
            if (index === 0) {
                backtrack(i + 1, currentStr, currentNum, currentNum);
            } else {
                // Try adding '+' operator
                backtrack(i + 1, `${path}+${currentStr}`, currentEval + currentNum, currentNum);
                
                // Try adding '-' operator
                backtrack(i + 1, `${path}-${currentStr}`, currentEval - currentNum, -currentNum);
                
                // Try adding '*' operator
                // The new evaluation is (currentEval - lastOperand) + (lastOperand * currentNum)
                backtrack(i + 1, `${path}*${currentStr}`, (currentEval - lastOperand) + (lastOperand * currentNum), lastOperand * currentNum);
            }
        }
    }

    backtrack(0, "", 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.