← 返回 instacart 的题目列表Onsite Coding: Expression Evaluation with Variables
类型:qbank
A recurring onsite coding prompt combining calculator parsing with variable assignment / equation evaluation. Examples include `A = 5`, `B = A`, `C = 5`, `D = C - 10`; variants ask for DFS over variable dependencies.
Requirements
Input is a set of variable definitions or equations plus arithmetic expressions.
Variables can point to numeric literals or to other variables.
Expressions include simple + and -; some variants are close to basic calculator and may include parentheses.
Return the evaluated value for a requested variable or expression.
Detect undefined variables and cycles if the interviewer asks for robustness.
Example shape:
A = 5
B = A
C = 5
D = C - 10
query D -> -5
DFS variant:
equations = [["a", "b"], ["b", "c"]]
values = [2.0, 3.0]
query a / c -> 6.0
Notes
Split the problem into parsing and evaluation. Store each variable as an expression AST or a token list; then evaluate with memoized DFS.
For simple +/-, a stack or running sign * value accumulator is enough. Parentheses require recursive descent or the standard stack-based Basic Calculator pattern.
For equation-division variants, build a weighted graph and run DFS/BFS from numerator to denominator, multiplying edge weights along the path.
Cycle handling: maintain visiting and visited sets. If a variable is encountered while already visiting, return an error / unknown value rather than recursing forever.
Complexity: parsing is O(total input length). Evaluation is O(V + E) for graph/equation variants and O(length) per expression with memoization over variables.
Preparation
Drill Basic Calculator, Evaluate Division, and a tiny variable-substitution parser.
Practice explaining why parsing into tokens first is safer than doing repeated string replacement.
Prepare tests for chained variables, undefined variables, a negative result, and a cycle.