Basic Calculator IV - Problem
Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"].
An expression alternates chunks and symbols, with a space separating each chunk and symbol. A chunk is either an expression in parentheses, a variable, or a non-negative integer. A variable is a string of lowercase letters (not including digits).
Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.
The format of the output is as follows:
- For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically
- Terms have degrees equal to the number of free variables being multiplied, counting multiplicity
- We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient
- The leading coefficient is placed directly to the left with an asterisk separating it from the variables
- A leading coefficient of 1 is still printed
- Terms with coefficient 0 are not included
Input & Output
Example 1 — Basic Expression with Substitution
$
Input:
expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
›
Output:
["-1*a","14"]
💡 Note:
Substitute e=1: 1 + 8 - a + 5 = 14 - a. Terms sorted by degree (variables first), then lexicographically.
Example 2 — Multiplication
$
Input:
expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12]
›
Output:
["-1*pressure","5"]
💡 Note:
Substitute e=1, temperature=12: 1 - 8 + 12 - pressure = 5 - pressure
Example 3 — Complex Expression
$
Input:
expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
›
Output:
["-64","1*e*e"]
💡 Note:
Expand (e+8)(e-8) = e² - 64. Sort by degree: e² has degree 2, constant -64 has degree 0.
Constraints
- 1 ≤ expression.length ≤ 250
- expression consists of lowercase English letters, digits, '+', '-', '*', '(', ')', and ' '
- 1 ≤ evalvars.length ≤ 100
- 1 ≤ evalvars[i].length ≤ 20
- evalvars[i] consists of lowercase English letters
- -100 ≤ evalints[i] ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code