Basic Calculator IV

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.

  • 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. Variables can be multiple letters, and variables never have a leading coefficient or unary operator like "2x" or "-x".

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, 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. Write the largest degree terms first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
  • The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables, if they exist. A leading coefficient of 1 is still printed.
  • Terms, including constant terms, with coefficient 0 are not included.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].

Example 1
Inputexpression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output["-1*a","14"]
Substituting e = 1 gives 1 + 8 - a + 5, which simplifies to -1*a + 14.
Example 2
Inputexpression = "e - 8 + temperature - pressure", evalvars = ["e","temperature"], evalints = [1,12]
Output["-1*pressure","5"]
Substituting e = 1 and temperature = 12 gives 1 - 8 + 12 - pressure, which simplifies to -1*pressure + 5.

Constraints

  • 1 <= expression.length <= 250
  • expression consists of lowercase English letters, digits, '+', '-', '*', '(', ')', ' '.
  • expression does not contain any leading or trailing spaces.
  • All the tokens in expression are separated by a single space.
  • 0 <= evalvars.length <= 100
  • 1 <= evalvars[i].length <= 20
  • evalvars[i] consists of lowercase English letters.
  • evalints.length == evalvars.length
  • -100 <= evalints[i] <= 100

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate