Skip to content

Practice Parse Lisp Expression

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#736
LeetCode Problem

Parse Lisp Expression

Problem Statement

Evaluate the valid Lisp-like expression and return its integer value. An expression is a signed integer, an assigned variable, or a parenthesized let, add or mult form. (add e1 e2) adds two evaluated expressions; (mult e1 e2) multiplies them. In (let v1 e1 v2 e2 ... vn en result), assign the variables in order, so later assignments can use earlier ones, then evaluate result within that scope. A variable starts with a lowercase letter followed by lowercase letters or digits; let, add and mult are reserved names. Resolve variables in the innermost enclosing scope first, then search outward. Nested scopes do not change an outer binding.

Source: Parse Lisp Expression on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"
Output
14

# Example 2

Input
expression = "(let x 3 x 2 x)"
Output
2

# Example 3

Input
expression = "(let x 1 y 2 x (add x y) (add x y))"
Output
5

Constraints

1 <= expression.length <= 2000
There are no leading or trailing spaces in expression.
All tokens are separated by a single space in expression.
The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.
The expression is guaranteed to be legal and evaluate to an integer.

Related LeetCode Problems

Practice more problems similar to Parse Lisp Expression.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.