Parse Lisp Expression - Problem

You are given a string expression representing a Lisp-like expression. Your task is to return the integer value after evaluating this expression.

Expression Types:

  • Integer: A positive or negative integer
  • Variable: A string starting with lowercase letter, followed by lowercase letters or digits
  • Let Expression: (let v1 e1 v2 e2 ... vn en expr) - assigns variables sequentially, then evaluates expr
  • Add Expression: (add e1 e2) - returns sum of two expressions
  • Mult Expression: (mult e1 e2) - returns product of two expressions

Scoping Rules: Variables are resolved from innermost to outermost scope. The names add, let, and mult are reserved and will never be used as variable names.

Input & Output

Example 1 — Let Expression
$ Input: expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"
Output: 14
💡 Note: Outer scope: x=2. Inner scope: x=3, y=4. Inner expression: add(3,4)=7. Outer expression: mult(2,7)=14.
Example 2 — Nested Add
$ Input: expression = "(add 1 (mult 2 3))"
Output: 7
💡 Note: First evaluate mult(2,3)=6, then add(1,6)=7.
Example 3 — Variable Scoping
$ Input: expression = "(let x 3 x 2 x)"
Output: 2
💡 Note: Variable x is reassigned: first x=3, then x=2. Final expression evaluates x which is 2.

Constraints

  • 1 ≤ expression.length ≤ 2000
  • The expression is syntactically correct
  • All integers are within the 32-bit signed integer range

Visualization

Tap to expand
Parse Lisp Expression INPUT (let x 2 (mult x ...)) let x=2 mult body x let x=3 y=4 add (let x 2 (mult x (let x 3 y 4 (add x y)))) ALGORITHM STEPS 1 Parse Token Identify: let, add, mult, var 2 Manage Scope Push/pop variable bindings 3 Recursive Eval Evaluate nested expressions 4 Compute Result Apply operations Evaluation Trace: Outer: x = 2 Inner: x = 3, y = 4 add(x,y) = add(3,4) = 7 Pop inner scope: x = 2 mult(x,7) = mult(2,7) = 14 Result: 14 FINAL RESULT Computation Flow: let x=2 scope: {x:2} let x=3, y=4 scope: {x:3,y:4} add(3,4) = 7 mult(2,7) = 14 Output: 14 OK - Verified Key Insight: Lisp expression parsing requires recursive descent with proper scope management. Each 'let' creates a new scope that shadows outer variables. Use a stack-based approach: push bindings when entering 'let', evaluate the body, then pop to restore outer scope. Inner x=3 shadows outer x=2 during add evaluation. TutorialsPoint - Parse Lisp Expression | Optimal Solution - Recursive Descent Parser
Asked in
Google 12 Microsoft 8 Amazon 6
18.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen