Parse Lisp Expression

HardStringssimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Evaluate a Lisp-like expression given as a string and return its integer value. An expression is one of: - An **integer**, possibly negative, such as 7 or -12. - A **variable** name: a lowercase letter followed by zero or more lowercase letters or digits. Its value is the one bound in the innermost enclosing scope. The names add, let and mul are never used as variables. - (add e1 e2): the sum of e1 and e2. (mul e1 e2): their product. - (let v1 e1 v2 e2 ... vn en expr): bind v1 to the value of e1, then v2 to e2, and so on in order, then return the value of expr. Each assignment can see the bindings made before it in the same let, and a later assignment to the same name overwrites the earlier one. Every let opens a new scope; its bindings disappear once the let finishes, and names from outer scopes are hidden while it runs. Tokens are separated by single spaces. The input is always a valid expression, and every value fits in a signed 32-bit integer.

Examples

Input: expression = "(let x 2 (mul x (let x 3 y 4 (add x y))))"
Output: 14
Inside the inner let, x is 3 and y is 4, so it yields 7. The outer mul uses the outer x = 2: 2 * 7 = 14.
Input: expression = "(let x 3 x 2 x)"
Output: 2
x is bound to 3 and then rebound to 2 before being returned.
Input: expression = "(let x 1 y 2 x (add x y) (add x y))"
Output: 5
x = 1, y = 2, then x = 1 + 2 = 3; the final expression is 3 + 2 = 5.

Constraints

  • 1 <= expression.length <= 2000
  • Tokens are separated by exactly one space, with no leading or trailing spaces
  • The expression is valid and every variable is bound before use
  • All intermediate values and the result fit in a signed 32-bit integer

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems