KatInterview

736. Parse Lisp Expression

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 requires us to evaluate a Lisp-like expression given as a string. These expressions can be integers, variables, or compound expressions for addition (add), multiplication (mult), and variable assignment (let). The core challenges are parsing the nested structure of these expressions and managing variable scopes correctly. A variable's value is determined by the innermost scope it's defined in. let expressions introduce new variables or shadow existing ones within their scope, and their assignments are processed sequentially.

Solution

Parse Lisp Expression in Python

class Solution:
    def evaluate(self, expression: str) -> int:
        # The main entry point, starts with an empty scope.
        return self._eval(expression, {})

    def _parse(self, s: str) -> list[str]:
        # Helper to parse the expression string into tokens.
        tokens = []
        i, n = 0, len(s)
        while i < n:
            token_start = i
            if s[i] == '(':
                # For a sub-expression, find the matching parenthesis.
                balance = 1
                i += 1
                while balance > 0:
                    if s[i] == '(':
                        balance += 1
                    elif s[i] == ')':
                        balance -= 1
                    i += 1
                tokens.append(s[token_start:i])
            else:
                # For a variable or number, find the next space.
                try:
                    space_idx = s.index(' ', token_start)
                    tokens.append(s[token_start:space_idx])
                    i = space_idx
                except ValueError:
                    # Last token in the string.
                    tokens.append(s[token_start:])
                    break
            
            if i < n and s[i] == ' ':
                i += 1 # Skip space to get to the next token.
        return tokens

    def _eval(self, expr: str, scope: dict[str, int]) -> int:
        # Case 1: Integer or variable.
        if not expr.startswith('('):
            if expr.isdigit() or expr.startswith('-'):
                return int(expr)
            return scope[expr]
        
        # Case 2: Compound expression `(op ...)`.
        content = expr[1:-1]
        first_space = content.find(' ')
        op = content[:first_space]
        rest = content[first_space+1:]
        
        tokens = self._parse(rest)
        
        if op == 'add':
            v1 = self._eval(tokens[0], scope)
            v2 = self._eval(tokens[1], scope)
            return v1 + v2
        elif op == 'mult':
            v1 = self._eval(tokens[0], scope)
            v2 = self._eval(tokens[1], scope)
            return v1 * v2
        else: # 'let' expression
            let_scope = scope.copy() # Create a new scope for this 'let' context.
            for i in range(0, len(tokens) - 1, 2):
                var_name = tokens[i]
                val_expr = tokens[i+1]
                var_val = self._eval(val_expr, let_scope)
                let_scope[var_name] = var_val
            return self._eval(tokens[-1], let_scope)

Parse Lisp Expression in Java

class Solution {
    public int evaluate(String expression) {
        return eval(expression, new HashMap<String, Integer>());
    }

    private int eval(String expr, Map<String, Integer> parentScope) {
        // Case 1: Integer or variable
        if (expr.charAt(0) != '(') {
            if (Character.isDigit(expr.charAt(0)) || expr.charAt(0) == '-') {
                return Integer.parseInt(expr);
            }
            return parentScope.get(expr);
        }

        // Case 2: Compound expression `(op ...)`
        String content = expr.substring(1, expr.length() - 1);
        int firstSpace = content.indexOf(' ');
        String op = content.substring(0, firstSpace);
        String rest = content.substring(firstSpace + 1);

        List<String> tokens = parse(rest);

        if (op.equals("add")) {
            int v1 = eval(tokens.get(0), parentScope);
            int v2 = eval(tokens.get(1), parentScope);
            return v1 + v2;
        } else if (op.equals("mult")) {
            int v1 = eval(tokens.get(0), parentScope);
            int v2 = eval(tokens.get(1), parentScope);
            return v1 * v2;
        } else { // "let" expression
            Map<String, Integer> scope = new HashMap<>(parentScope); // Create a new scope
            for (int i = 0; i < tokens.size() - 1; i += 2) {
                String varName = tokens.get(i);
                String valExpr = tokens.get(i + 1);
                int varVal = eval(valExpr, scope); // Use current state of scope for evaluation
                scope.put(varName, varVal); // Update scope for subsequent assignments
            }
            return eval(tokens.get(tokens.size() - 1), scope);
        }
    }

    // Helper to parse the expression string into tokens
    private List<String> parse(String content) {
        List<String> tokens = new ArrayList<>();
        int i = 0;
        while (i < content.length()) {
            int tokenStart = i;
            if (content.charAt(tokenStart) == '(') {
                int balance = 1;
                i++;
                while (i < content.length() && balance > 0) {
                    if (content.charAt(i) == '(') balance++;
                    else if (content.charAt(i) == ')') balance--;
                    i++;
                }
                tokens.add(content.substring(tokenStart, i));
            } else {
                int spaceIdx = content.indexOf(' ', tokenStart);
                if (spaceIdx == -1) {
                    tokens.add(content.substring(tokenStart));
                    break; // Last token
                } else {
                    tokens.add(content.substring(tokenStart, spaceIdx));
                    i = spaceIdx;
                }
            }
            // Move to the start of the next token
            if (i < content.length() && content.charAt(i) == ' ') {
                i++;
            }
        }
        return tokens;
    }
}

Parse Lisp Expression in C++

class Solution {
public:
    int evaluate(string expression) {
        unordered_map<string, int> scope;
        return eval(expression, scope);
    }

private:
    // Helper function to parse the expression string into tokens.
    vector<string> parse(const string& s) {
        vector<string> tokens;
        int i = 0;
        while (i < s.length()) {
            int start = i;
            if (s[i] == '(') {
                int balance = 1;
                i++;
                while (i < s.length() && balance > 0) {
                    if (s[i] == '(') balance++;
                    else if (s[i] == ')') balance--;
                    i++;
                }
                tokens.push_back(s.substr(start, i - start));
            } else {
                size_t space_pos = s.find(' ', start);
                if (space_pos == string::npos) {
                    tokens.push_back(s.substr(start));
                    break; // Last token
                } else {
                    tokens.push_back(s.substr(start, space_pos - start));
                    i = space_pos;
                }
            }
            if (i < s.length() && s[i] == ' ') {
                i++; // Skip the space after a token
            }
        }
        return tokens;
    }

    // Recursive evaluation function.
    int eval(const string& expr, const unordered_map<string, int>& parentScope) {
        // Case 1: Integer or variable.
        if (expr[0] != '(') {
            if (isdigit(expr[0]) || expr[0] == '-') {
                return stoi(expr);
            }
            return parentScope.at(expr);
        }

        // Case 2: Compound expression `(op ...)`.
        string content = expr.substr(1, expr.length() - 2);
        size_t first_space = content.find(' ');
        string op = content.substr(0, first_space);
        string rest = content.substr(first_space + 1);

        if (op == "add" || op == "mult") {
            vector<string> tokens = parse(rest);
            int v1 = eval(tokens[0], parentScope);
            int v2 = eval(tokens[1], parentScope);
            return (op == "add") ? (v1 + v2) : (v1 * v2);
        } else { // "let" expression
            unordered_map<string, int> scope = parentScope; // Create a new scope
            vector<string> tokens = parse(rest);
            for (size_t i = 0; i < tokens.size() - 1; i += 2) {
                string var_name = tokens[i];
                string val_expr = tokens[i+1];
                scope[var_name] = eval(val_expr, scope);
            }
            return eval(tokens.back(), scope);
        }
    }
};

Parse Lisp Expression in TypeScript

function evaluate(expression: string): number {
    const parse = (s: string): string[] => {
        const tokens: string[] = [];
        let i = 0;
        while (i < s.length) {
            const start = i;
            if (s[i] === '(') {
                let balance = 1;
                i++;
                while (i < s.length && balance > 0) {
                    if (s[i] === '(') balance++;
                    else if (s[i] === ')') balance--;
                    i++;
                }
                tokens.push(s.substring(start, i));
            } else {
                const spaceIdx = s.indexOf(' ', start);
                if (spaceIdx === -1) {
                    tokens.push(s.substring(start));
                    break;
                } else {
                    tokens.push(s.substring(start, spaceIdx));
                    i = spaceIdx;
                }
            }
            if (i < s.length && s[i] === ' ') {
                i++;
            }
        }
        return tokens;
    };

    const evalExpr = (expr: string, parentScope: Map<string, number>): number => {
        // Case 1: Integer or variable
        if (expr[0] !== '(') {
            if ((expr[0] >= '0' && expr[0] <= '9') || expr[0] === '-') {
                return parseInt(expr);
            }
            return parentScope.get(expr)!;
        }

        // Case 2: Compound expression
        const content = expr.substring(1, expr.length - 1);
        const firstSpace = content.indexOf(' ');
        const op = content.substring(0, firstSpace);
        const rest = content.substring(firstSpace + 1);

        const tokens = parse(rest);

        if (op === "add") {
            const v1 = evalExpr(tokens[0], parentScope);
            const v2 = evalExpr(tokens[1], parentScope);
            return v1 + v2;
        } else if (op === "mult") {
            const v1 = evalExpr(tokens[0], parentScope);
            const v2 = evalExpr(tokens[1], parentScope);
            return v1 * v2;
        } else { // "let" expression
            const scope = new Map(parentScope);
            for (let i = 0; i < tokens.length - 1; i += 2) {
                const varName = tokens[i];
                const valExpr = tokens[i + 1];
                const varVal = evalExpr(valExpr, scope);
                scope.set(varName, varVal);
            }
            return evalExpr(tokens[tokens.length - 1], scope);
        }
    };

    return evalExpr(expression, new Map());
}

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.