Ctrl K

A Calculator With Brackets and Variables

Hard
You are given a string program written in a tiny bracket-based language. Evaluate it and return the resulting integer. An expression is one of the following: - an integer, possibly negative, such as 7 or -12; - a variable name: a lowercase letter followed by zero or more lowercase letters or digits; - (add e1 e2): the sum of the values of e1 and e2; - (mult e1 e2): the product of the values of e1 and e2; - (let v1 e1 v2 e2 ... vk ek body): assigns the value of e1 to v1, then the value of e2 to v2, and so on (each expression already sees the earlier assignments), and then returns the value of body. There is at least one name–expression pair. Every let opens its own scope: assignments made inside it are not visible outside. When a variable name is evaluated, its value comes from the nearest enclosing scope that defines it. The words add, mult and let are never used as variable names. Tokens are separated by exactly one space, and the expression is always well formed.
Example 1
program="(add 3 (mult 4 5))" → 23

First 4 · 5 = 20, then 3 + 20 = 23.

Example 2
program="(let a 5 (add a (let a 10 (mult a 2))))" → 25

The inner let creates its own a = 10, so (mult a 2) gives 20. Outside, a is still 5, and the answer is 5 + 20 = 25.

Example 3
program="(let n 2 n (mult n n) n (add n -1) n)" → 3

Assignments run in order: n = 2, then 2 · 2 = 4, then 4 − 1 = 3.

Constraints
  • 1 ≤ len(program) ≤ 2000
  • No leading or trailing spaces; tokens are separated by a single space
  • The expression is well formed and every variable it uses is defined
  • The answer and every intermediate value fit in a signed 32-bit integer
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSimplify a Letter Polynomial HardPlus-Minus Calculator With Brackets HardElement Tally From a Formula HardCalculator With Brackets and Four Operations HardA Nested Logic Formula Hard
loading Python…
Input
program="(add 3 (mult 4 5))"
Expected
23

Run checks the first 3 tests in your browser. Submit checks all 91 tests on the server, hidden ones included.