Practice/Google/Leetcode 770. Basic Calculator IV
CodingMust
Build a symbolic expression evaluator that handles arithmetic expressions containing integers, variables (multi-character identifiers), and the operators +, -, and *. The evaluator must:
The expression string contains space-separated tokens. Variable assignments are given as strings in the format "variable=value".
Parse and evaluate the expression with correct operator precedence
Handle parentheses for grouping operations
Substitute only the variables that appear in the evaluation map
Expand all products fully (e.g., (a+b)*c becomes a*c + b*c)
Combine terms with the same variables (e.g., 2*x + 3*x becomes 5*x)
Drop any terms whose coefficient becomes zero
Sort output terms by:
Format each term as coefficient*var1*var2*... (or just coefficient for constants)
Example 1:
Input: expression = "a + b", evalMap = ["a=5", "b=3"] Output: "8" Explanation: Both variables are substituted, resulting in 5+3=8
Example 2:
Input: expression = "x * y + z", evalMap = [] Output: "x*y+z" Explanation: No substitutions. Two terms: degree-2 term "x*y" comes before degree-1 term "z"
Example 3:
Input: expression = "(a + b) * (c + d)", evalMap = ["a=1"] Output: "b*c+b*d+c+d" Explanation: Expand (1+b)*(c+d) = c + d + b*c + b*d. Sort by degree then lexicographically: b*c, b*d (both degree 2), then c, d (degree 1)
Example 4:
Input: expression = "x - x", evalMap = [] Output: "0" Explanation: The terms cancel out, leaving only the constant 0