Skip to content

Practice Basic Calculator IV

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#770
LeetCode Problem

Basic Calculator IV

Problem Statement

Simplify expression after substituting each evalvars name with the corresponding evalints integer. Input chunks are nonnegative integers, lowercase-letter variable names or parenthesized expressions, separated from operators by spaces. Variables have no attached coefficient or unary sign. Apply parentheses first, then multiplication, then addition and subtraction. Combine like terms. Within each term, sort variable names lexicographically, retaining repeated factors. Output terms by decreasing degree, breaking ties lexicographically by their variable factors. Write the signed coefficient first, even when it is 1, with * between it and each variable. Write constants without variables, and omit every zero-coefficient term; zero therefore returns an empty list. Input is valid and intermediate values fit in signed 32-bit integers.

Source: Basic Calculator IV on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output
["-1*a","14"]

# Example 2

Input
expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12]
Output
["-1*pressure","5"]

# Example 3

Input
expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output
["1*e*e","-64"]

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

Related LeetCode Problems

Practice more problems similar to Basic Calculator IV.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.