KatInterview

Build a Calculator with Variables, Unary Signs and Parentheses

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesparsingrecursive-descentexpression-evaluation

Last updated

Write a linear-time evaluator for integer expressions with variables, precedence, unary signs, parentheses, truncating division and 64-bit error handling.

Write a function that evaluates an arithmetic expression given as a string, using a dictionary of variable values.

Input

  • expr: a string made of non-negative integer literals, variable names (letters only), the operators +, -, *, /, parentheses ( and ), and space characters.
  • variables: a mapping from variable name to integer value.

Output

The value of the expression as a signed 64-bit integer.

Rules

  • * and / bind tighter than + and -.
  • Operators of equal precedence are applied left to right, so 8 - 3 - 2 is 3.
  • Unary + and - are allowed anywhere an operand may start, for example -x, 2 * -3 and --4.
  • Integer division truncates toward zero, so -7 / 2 gives -3, not -4.
  • Signal an error for an invalid character, a malformed expression, mismatched parentheses, an unknown variable, division by zero, or a result outside the signed 64-bit range.
  • Time must be O(L) and extra space O(L), where L is len(expr).

Examples

exprvariablesresult
"3 + 4 * 2"{}11
"(1 + 2) * 3"{}9
"2 * -x"{x: 4}-8
"-7 / 2"{}-3
"(1 + 2"{}error

Follow-ups

  1. Add exponentiation ^, which is right-associative.
  2. Add a two-argument function call max(a, b).

Describe your approach, give the complexity, and write the code.

Hints

Hint 1

Write the grammar down first, one rule per precedence level: sums of products, products of signed operands, and a base case of number, variable or parenthesised group. Each rule becomes a small function.

Hint 2

Tokenize the string in one pass before evaluating. Then evaluate directly while parsing, with no tree. Use a loop at each level to get left associativity, and call the unary rule for the right operand so that `2 * -3` works.

Hint 3

For truncating division, divide the absolute values and fix the sign yourself, because Python's `//` floors. After parsing, check that every token was consumed, which catches a stray `)` and input like `2 3`.