InterviewDB Question

Formula Numbers: Evaluate Arithmetic Expressions with Named Variables

Question Details

Problem

You are given a list of variable definitions of the form "name = expr" where expr is an arithmetic expression involving integer literals, +, -, *, /, parentheses, and previously defined variable names. Evaluate each definition in order and return the final value of a queried variable.

python
def evaluate_formula(definitions: list[str], query: str) -> float:
    """
    definitions: ["x = 3", "y = x + 2", "z = (x * y) - 1"]
    query: "z"
    """
    pass

**Input**:
  definitions = ["a = 4", "b = a * 2", "c = (a + b) / 3"]
  query = "c"

**Output**: 4.0
# a=4, b=8, c=(4+8)/3=4.0

**Input**:
  definitions = ["n = 10", "m = n - 3", "r = m * m"]
  query = "r"

**Output**: 49.0

Follow-ups

  1. How would you build a recursive descent parser for arithmetic expressions with operator precedence?
  2. What data structure holds the evaluated variable context during parsing?
  3. How do you detect and report undefined variable references?
  4. Extend to support built-in functions like sqrt(x) and abs(x) in expressions.

Full Details

Problem

You are given a list of variable definitions of the form "name = expr" where expr is an arithmetic expression involving integer literals, +, -, *, /, parentheses, and previously defined variable names. Evaluate each definition in order and return the final value of a queried variable.

python
def evaluate_formula(definitions: list[str], query: str) -> float:
    """
    definitions: ["x = 3", "y = x + 2", "z = (x * y) - 1"]
    query: "z"
    """
    pass

**Input**:
  definitions = ["a = 4", "b = a * 2", "c = (a + b) / 3"]
  query = "c"

**Output**: 4.0
# a=4, b=8, c=(4+8)/3=4.0

**Input**:
  definitions = ["n = 10", "m = n - 3", "r = m * m"]
  query = "r"

**Output**: 49.0

Follow-ups

  1. How would you build a recursive descent parser for arithmetic expressions with operator precedence?
  2. What data structure holds the evaluated variable context during parsing?
  3. How do you detect and report undefined variable references?
  4. Extend to support built-in functions like sqrt(x) and abs(x) in expressions.

About This Question

This is a reported interview question from a zoox interview during the onsite round.

It covers the following topics: Recursion, Coding, Onsite .