KatInterview

Evaluate Nested Prefix Expressions with Scoped Bindings

Stacks & QueuesAuto-graded · 28 test cases
MediumAuto-gradedStacks & Queuesparsingrecursionscoping

Last updated

Parse and evaluate a parenthesized prefix language with sum, prod and set, handling lexical scoping, strict validation and 32-bit overflow rules.

Evaluate Nested Prefix Expressions with Scoped Bindings

You are given a string expr written in a small Lisp-like language. Compute its integer value. If the string is not a valid program, return the string "InvalidExpression" instead.

The language

An expression is either an atom or a parenthesized form.

Atoms

  • An integer matches -?[0-9]+: an optional leading - followed by one or more ASCII digits. Leading zeros are allowed, so 007 is 7 and -0 is 0.
  • A variable matches [a-z][a-z0-9]*: a lowercase letter followed by any number of lowercase letters or digits.
  • Any other atom (for example 1a, --1, -, +3, X, a_b) is malformed.

Parenthesized forms have the shape ( op ... ), where op is the first token after the opening parenthesis:

  • (sum e1 e2 ... ek) with k >= 2 returns the sum of its sub-expressions.
  • (prod e1 e2 ... ek) with k >= 2 returns the product of its sub-expressions.
  • (set x v body) takes exactly three parts. x must be a raw variable token (not a parenthesized form). v and body are arbitrary expressions. The form first evaluates v, then evaluates body with x bound to that value, and returns the value of body.

Any other token in operator position is an error.

Scoping

  • Bindings are lexical. x is visible only inside the body of its set, including any forms nested in that body.
  • An inner set of the same name shadows the outer binding for its own body only.
  • v is evaluated in the scope outside the new binding. For example, (set x 1 (set x (sum x 1) x)) is 2.
  • Once a set form closes, its binding is gone.
  • Variable names are not restricted. A name such as sum may be bound by set and then read as an ordinary variable atom. A token directly after ( is always treated as the operator.

Tokenization

Parentheses are separate tokens even when they touch other text, so (sum 1 2) has the tokens (, sum, 1, 2, ). Any run of whitespace separates tokens, and extra whitespace is ignored. Every other maximal run of non-whitespace, non-parenthesis characters is one token.

32-bit range

Every value must stay within the signed 32-bit range [-2147483648, 2147483647]. A violation makes the whole expression invalid. The checks are:

  • Each integer literal must be in range.
  • For sum, only the final total of that form is checked. Intermediate partial sums are not checked, so (sum 2147483647 1 -1) is 2147483647.
  • For prod, the arguments are multiplied left to right, starting from a running value of 1, and every running product must be in range. So (prod 65536 65536 0) is invalid even though the true product is 0.

Errors

Return "InvalidExpression" when any of these occurs:

  • The input is empty or contains only whitespace.
  • Parentheses are unbalanced, there is a stray ), or tokens remain after the top-level expression is complete (for example 1 2 or (sum 1 2))).
  • () is given, or the operator is unknown.
  • A form has the wrong arity or shape, including set whose first argument is not a variable token.
  • A variable is referenced while no binding for it is in scope.
  • A malformed atom appears.
  • The 32-bit rules above are violated.

A bare atom such as 5 is a valid whole expression.

Task

Implement evaluate_expression(expr). It returns the integer value of a valid expression, or the string "InvalidExpression" otherwise.

Constraints

  • 0 <= len(expr) <= 10^5
  • Maximum nesting depth is at most 10^4.
  • The return value is either an int or the exact string "InvalidExpression".

Examples

Example 1

Input: evaluate_expression('(sum 1 2)')

Output: 3

Example 2

Input: evaluate_expression('(prod 2 (sum 3 4) -2)')

Output: -28

Example 3

Input: evaluate_expression('(set x 3 (sum x (set x 5 x)))')

Output: 8

Example 4

Input: evaluate_expression('(sum 1)')

Output: 'InvalidExpression'

Hints

Hint 1

Tokenize first with a regular expression that yields '(' , ')' and runs of other non-whitespace characters, so touching parentheses are handled and empty input is easy to detect.

Hint 2

Write a recursive parse function that consumes one expression from a token index and returns its value. Read the operator right after '(', then loop until ')' for sum/prod, and handle set as name, value, body, then ')'.

Hint 3

For scoping, pass a mapping down the recursion. In set, evaluate the value in the current mapping, then evaluate the body in a copy extended with the new name. Be careful about where overflow is checked: every literal, the final sum, and every running product.