#770
Hard Algorithms Basic calculator iv
Hash Table Math String Stack Recursion
49.7% acceptance
Feb 21, 2026
181
1446
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.) Note that variables can be multiple letters, and note that 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.
For example, expression = "1 + 2 * 3" has an answer of ["7"].
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.
For example, we would never write a term like "b*a*c", only "a*b*c".
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 of the term.
For example, "a*a*b*c" has degree 4.
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.
An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"].
Terms (including constant terms) with coefficient 0 are not included.
For example, an expression of "0" has an output of [].
Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Solution
Rust
Time O(n²)
Space O(n)
/*
* 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.) Note that variables can be multiple letters, and note that 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.
* For example, expression = "1 + 2 * 3" has an answer of ["7"].
* 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.
* For example, we would never write a term like "b*a*c", only "a*b*c".
* 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 of the term.
* For example, "a*a*b*c" has degree 4.
* 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.
* An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"].
* Terms (including constant terms) with coefficient 0 are not included.
* For example, an expression of "0" has an output of [].
* Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
* 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
*/
use std::collections::HashMap;
type Poly = HashMap<Vec<String>, i64>;
fn poly_const(c: i64) -> Poly {
let mut p = HashMap::new();
if c != 0 { p.insert(vec![], c); }
p
}
fn poly_var(v: String) -> Poly {
let mut p = HashMap::new();
p.insert(vec![v], 1);
p
}
fn poly_add(mut a: Poly, b: Poly) -> Poly {
for (k, v) in b { *a.entry(k).or_insert(0) += v; }
a.retain(|_, v| *v != 0);
a
}
fn poly_sub(mut a: Poly, b: Poly) -> Poly {
for (k, v) in b { *a.entry(k).or_insert(0) -= v; }
a.retain(|_, v| *v != 0);
a
}
fn poly_mul(a: Poly, b: Poly) -> Poly {
let mut res: Poly = HashMap::new();
for (ka, va) in &a {
for (kb, vb) in &b {
let mut k: Vec<String> = ka.iter().chain(kb.iter()).cloned().collect();
k.sort();
*res.entry(k).or_insert(0) += va * vb;
}
}
res.retain(|_, v| *v != 0);
res
}
fn poly_to_strings(p: &Poly) -> Vec<String> {
let mut terms: Vec<(&Vec<String>, i64)> = p.iter().map(|(k, &v)| (k, v)).collect();
terms.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.join("*").cmp(&b.0.join("*"))));
terms.iter().map(|(vars, coeff)| {
if vars.is_empty() { format!("{}", coeff) } else { format!("{}*{}", coeff, vars.join("*")) }
}).collect()
}
fn calc_parse_expr(chars: &[char], pos: &mut usize, scope: &HashMap<String, i64>) -> Poly {
let mut result = calc_parse_term(chars, pos, scope);
while *pos < chars.len() && chars[*pos] == ' ' { *pos += 1; }
while *pos < chars.len() && (chars[*pos] == '+' || chars[*pos] == '-') {
let op = chars[*pos]; *pos += 1;
while *pos < chars.len() && chars[*pos] == ' ' { *pos += 1; }
let right = calc_parse_term(chars, pos, scope);
result = if op == '+' { poly_add(result, right) } else { poly_sub(result, right) };
while *pos < chars.len() && chars[*pos] == ' ' { *pos += 1; }
}
result
}
fn calc_parse_term(chars: &[char], pos: &mut usize, scope: &HashMap<String, i64>) -> Poly {
let mut result = calc_parse_factor(chars, pos, scope);
while *pos < chars.len() && chars[*pos] == ' ' { *pos += 1; }
while *pos < chars.len() && chars[*pos] == '*' {
*pos += 1;
while *pos < chars.len() && chars[*pos] == ' ' { *pos += 1; }
let right = calc_parse_factor(chars, pos, scope);
result = poly_mul(result, right);
while *pos < chars.len() && chars[*pos] == ' ' { *pos += 1; }
}
result
}
fn calc_parse_factor(chars: &[char], pos: &mut usize, scope: &HashMap<String, i64>) -> Poly {
if chars[*pos] == '(' {
*pos += 1;
while *pos < chars.len() && chars[*pos] == ' ' { *pos += 1; }
let result = calc_parse_expr(chars, pos, scope);
while *pos < chars.len() && chars[*pos] == ' ' { *pos += 1; }
*pos += 1; // ')'
result
} else if chars[*pos].is_ascii_digit() {
let start = *pos;
while *pos < chars.len() && chars[*pos].is_ascii_digit() { *pos += 1; }
let n: i64 = chars[start..*pos].iter().collect::<String>().parse().unwrap();
poly_const(n)
} else {
let start = *pos;
while *pos < chars.len() && chars[*pos].is_ascii_lowercase() { *pos += 1; }
let var: String = chars[start..*pos].iter().collect();
if let Some(&v) = scope.get(&var) { poly_const(v) } else { poly_var(var) }
}
}
impl Solution {
pub fn basic_calculator_iv(expression: String, evalvars: Vec<String>, evalints: Vec<i32>) -> Vec<String> {
let scope: HashMap<String, i64> = evalvars.iter().cloned()
.zip(evalints.iter().map(|&x| x as i64)).collect();
let chars: Vec<char> = expression.chars().collect();
let mut pos = 0usize;
while pos < chars.len() && chars[pos] == ' ' { pos += 1; }
let result = calc_parse_expr(&chars, &mut pos, &scope);
poly_to_strings(&result)
}
}