Basic Calculator IV LeetCode Solution

Last updated on October 9th, 2024 at 06:23 pm

Here, We see Basic Calculator IV LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Graph, Greedy, Union-Find

Level of Question

Hard

Basic Calculator IV LeetCode Solution

Basic Calculator IV LeetCode Solution

Problem Statement

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″]

1. Basic Calculator IV LeetCode Solution C++

class Solution {
public:
    vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {
        unordered_map<string, int> mp;
        int n = evalvars.size();
        for (int i = 0; i < n; ++i) mp[evalvars[i]] = evalints[i];
        int pos = 0;
        unordered_map<string, int> output = helper(expression, mp, pos);
        vector<pair<string, int>> ans(output.begin(), output.end());
        sort(ans.begin(), ans.end(), mycompare);
        vector<string> res;
        for (auto& p: ans) {
            if (p.second == 0) continue;
            res.push_back(to_string(p.second));
            if (p.first != "") res.back() += "*"+p.first;
        }
        return res;
    }
private:
    unordered_map<string, int> helper(string& s, unordered_map<string, int>& mp, int& pos) {
        vector<unordered_map<string, int>> operands;
        vector<char> ops;
        ops.push_back('+');
        int n = s.size();
        while (pos < n && s[pos] != ')') {
            if (s[pos] == '(') {
               pos++;
               operands.push_back(helper(s, mp, pos));
            }
            else {
               int k = pos;
               while (pos < n && s[pos] != ' ' && s[pos] != ')') pos++;
               string t = s.substr(k, pos-k);
               bool isNum = true;
               for (char c: t) {
                   if (!isdigit(c)) isNum = false;
               }
               unordered_map<string, int> tmp;
               if (isNum) 
                   tmp[""] = stoi(t);
               else if (mp.count(t)) 
                   tmp[""] = mp[t];
               else              
                   tmp[t] = 1;
               operands.push_back(tmp);
            }
            if (pos < n && s[pos] == ' ') {
               ops.push_back(s[++pos]);
               pos += 2;
            }
        }
        pos++;
        return calculate(operands, ops);
    }
    unordered_map<string, int> calculate(vector<unordered_map<string, int>>& operands, vector<char>& ops) {
        unordered_map<string, int> ans;
        int n = ops.size();
        for (int i = n-1; i >= 0; --i) {
            unordered_map<string, int> tmp = operands[i];
            while (i >= 0 && ops[i] == '*')
                tmp = multi(tmp, operands[--i]);
            int sign = ops[i] == '+'? 1: -1;
            for (auto& p: tmp) ans[p.first] += sign*p.second;
        }
        return ans;
    }
    unordered_map<string, int> multi(unordered_map<string, int>& lhs, unordered_map<string, int>& rhs) {
        unordered_map<string, int> ans;
        int m = lhs.size(), n = rhs.size();
        for (auto& p: lhs) {
            for (auto& q: rhs) {
                string t = combine(p.first, q.first);
                ans[t] += p.second*q.second;
            }
        }
        return ans;
    }
    string combine(const string& a, const string& b) {
        if (a == "") return b;
        if (b == "") return a;
        vector<string> strs = split(a, '*');
        for (auto& s: split(b, '*')) strs.push_back(s);
        sort(strs.begin(), strs.end());
        string s;
        for (auto& t: strs) s += t +'*';
        s.pop_back();
        return s;
    }
    static vector<string> split(const string& s, char c) {
        vector<string> ans;
        int i = 0, n = s.size();
        while (i < n) {
            int j = i;
            i = s.find(c, i);
            if (i == -1) i = n;
            ans.push_back(s.substr(j, i-j));
            i++;
        }
        return ans;
    }
    static bool mycompare(pair<string, int>& a, pair<string, int>& b) {
        string s1 = a.first, s2 = b.first;
        vector<string> left = split(s1, '*'); 
        vector<string> right = split(s2, '*');
        return left.size() > right.size() || (left.size() == right.size() && left < right);
    } 
};

2. Basic Calculator IV LeetCode Solution Java

class Solution {
    int n;
    String s;
    char[] arr;
    int[] braces;
    HashMap<String, Integer> variables = new HashMap<>();
    
    public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
        s = expression;
        arr = s.toCharArray();
        n = arr.length;
        braces = new int[n];
        Arrays.fill(braces, -1);
        int[] stack = new int[n/2];
        int index = -1;
        for(int i=0; i<n; ++i) {
            if(arr[i] == '(') stack[++index] = i;
            else if(arr[i] == ')') {
                int last = stack[index--];
                braces[last] = i;
                braces[i] = last;
            }
        }
        for(int i=0; i<evalvars.length; ++i) variables.put(evalvars[i], evalints[i]);
        List<Term> terms = dewIt(0, n-1);
        TreeMap<String, Integer> map = new TreeMap<>(new Comparator<>() {
            public int compare(String a, String b) {
                int ca = countStars(a), cb = countStars(b);
                if(ca != cb) return cb - ca;
                else return a.compareTo(b);
            }
            private int countStars(String s) {
                int ans = 0;
                for(char c: s.toCharArray()) if(c == '*') ++ans;
                return ans;
            }
        });
        for(Term term: terms) {
            if(term.coeff != 0) {
                String key = term.getKey();
                if(map.containsKey(key)) {
                    int oldCoeff = map.get(key);
                    if(oldCoeff == -term.coeff) map.remove(key);
                    else map.put(key, oldCoeff + term.coeff);
                } else map.put(key, term.coeff);
            }
        }
        List<String> ans = new LinkedList<>();
        for(String k: map.keySet()) ans.add(map.get(k) + "" + k);
        return ans;
    }
    private List<Term> dewIt(int a, int b) {
        if(braces[a] == b) return dewIt(a+1, b-1);
        List<Term> ans = new LinkedList<>(), buffer = new LinkedList<>();
        buffer.add(new Term(1, new LinkedList<>()));
        for(int i=a; i<=b; ) {
            int j = i;
            List<Term> curr = null;
            if(arr[i] == '(') {
                j = braces[i] + 1;
                curr = dewIt(i+1, j-2);
            }
            else {
                while(j <= b && arr[j] != ' ') ++j;
                String exp = s.substring(i, j);
                int val = 1;
                List<String> vars = new LinkedList<>();
                if(variables.containsKey(exp)) val = variables.get(exp);
                else if (exp.charAt(0) <= '9') val = Integer.valueOf(exp);
                else vars.add(exp);
                curr = new LinkedList<>();
                curr.add(new Term(val, vars));
            }
            buffer = multiply(buffer, curr);
            if(j > b || arr[j+1] == '+' || arr[j+1] == '-') {
                ans.addAll(buffer);
                buffer = new LinkedList<>();
            }
            if(j < b) {
                ++j;
                if(arr[j] == '+') buffer.add(new Term(1, new LinkedList<>()));
                else if(arr[j] == '-') buffer.add(new Term(-1, new LinkedList<>()));
                j += 2;
            }
            i = j;
        }
        return ans;
    }
    private List<Term> multiply(List<Term> a, List<Term> b) {
        List<Term> ans = new LinkedList<>();
        for(Term x: a) for(Term y: b) {
            Term prod = x.clone();
            prod.multiply(y);
            ans.add(prod);
        }
        return ans;
    }
}
class Term {
    int coeff;
    List<String> vars;

    public Term(int a, List<String> c) {
        this.coeff = a;
        vars = new LinkedList<>();
        vars.addAll(c);
    }
    public String getKey() {
        StringBuilder b = new StringBuilder();
        Collections.sort(vars);
        for(String x: vars) {
            b.append('*');
            b.append(x);
        }
        return b.toString();
    }
    public void multiply(Term that) {
        this.coeff *= that.coeff;
        if(this.coeff == 0) vars.clear();
        else this.vars.addAll(that.vars);
    }
    public Term clone() {
        return new Term(coeff, vars);
    }
}

3. Basic Calculator IV LeetCode Solution JavaScript

class Unit {
    constructor(count, val = []) {
        this.count = count
        this.val = val
        this.val.sort()
        this.valStr = this.val.join('*')
    }
    product(u1 = new Unit) {
        return new Unit(this.count * u1.count, this.val.concat(u1.val))
    }
    toString() {
        return this.count + (this.valStr ? '*' + this.valStr : '')
    }
}
class Exp {

    constructor(children = []) {
        this.children = []
        this.dic = new Map()
        for (let child of children) this.addUnit(child)
    }

    addUnit(u = new Unit) {
        let { dic, children } = this
        if (dic.has(u.valStr))
            children[dic.get(u.valStr)].count += u.count
        else {
            dic.set(u.valStr, children.length)
            children.push(u)
        }
    }

    product(exp1 = new Exp) {
        let exp = new Exp
        this.children.forEach(x => {
            exp1.children.forEach(y => {
                exp.addUnit(x.product(y))
            })
        })
        return exp
    }

    add(exp1 = new Exp) {
        exp1.children.forEach(x => this.addUnit(x))
        return this
    }

    toArray() {
        let group = new Map()
        for (let x of this.children) {
            if (!group.has(x.val.length)) group.set(x.val.length, [])
            x.count != 0 && group.get(x.val.length).push(x)
        }
        let groupArr = [...group.entries()].sort((a, b) => b[0] - a[0])
        return groupArr.map(([_, x]) => {
            x.sort((a, b) => a.valStr.localeCompare(b.valStr))
            return x.map(x => x.toString())
        }).flat()
    }
}

var basicCalculatorIV = function (expression, evalvars, evalints) {
    let tokens = toTokens(expression)
        .map(x => /^\d+$/.test(x) ? Number.parseInt(x) : x),
        vals = toVarDic(evalvars, evalints), i = 0

    let exp = nextExp()
    return exp.toArray()


    function nextExp() {
        if (i >= tokens.length) return undefined
        let [exp, op1] = [nextUnit(), nextOperator()]
        if (!op1 || op1 == ')') return exp
        let exp1 = nextUnit()
        while (true) {
            let op2 = nextOperator()
            if (!op2 || op2 == ')') return dealDefault()
            let exp2 = nextUnit()
            switch (op2) {
                case '+':
                case '-':
                    exp = dealDefault()
                    op1 = op2
                    exp1 = exp2
                    continue
                case '*':
                    exp1 = exp1.product(exp2)
                    continue
                default:
                    return dealDefault()
            }
            function dealDefault() {
                switch (op1) {
                    case '+':
                        return exp.add(exp1)
                    case '-':
                        let expz = exp1.product(new Exp([new Unit(-1, [])]))
                        return exp.add(expz)
                    case '*':
                        return exp.product(exp1)
                }
                debugger
            }
        }
    }


    function nextUnit() {
        if (i >= tokens.length) return undefined
        let rtn
        if (tokens[i] == '(') {
            i++
            return nextExp()
        }
        else if (Number.isInteger(tokens[i])) rtn = new Exp([
            new Unit(tokens[i], [])
        ])
        else if (vals.has(tokens[i])) rtn = new Exp([
            new Unit(vals.get(tokens[i]), [])
        ])
        else rtn = new Exp([
            new Unit(1, [tokens[i]])
        ])
        i++
        return rtn
    }
    function nextOperator() {
        if (i >= tokens.length) return undefined
        let op = tokens[i]
        i++
        return op
    }
};

function toTokens(str = '') {
    let tokens = [], tmp = '', keyWords = {
        '(': true,
        ')': true,
        '+': true,
        '*': true,
    }
    for (let char of str) {
        if (keyWords[char]) {
            if (tmp) tokens.push(tmp)
            tokens.push(char)
            tmp = ''
            continue
        }
        if (char == ' ') {
            if (tmp) {
                tokens.push(tmp)
                tmp = ''
            }
            continue
        }
        tmp += char
    }
    if (tmp) tokens.push(tmp)
    return tokens
}

function toVarDic(keys = [], vals = []) {
    let dic = new Map
    for (let i = 0; i < keys.length; i++) {
        dic.set(keys[i], vals[i])
    }
    return dic
}

4. Basic Calculator IV LeetCode Solution Python

from collections import deque, defaultdict

class Polynomial:
    def __init__(self, variables):
        self.variables = variables
        
    def __add__(self, other):
        new_variables = defaultdict(int)
        for name in self.variables:
            new_variables[name] += self.variables[name]
        for name in other.variables:
            new_variables[name] += other.variables[name]
        return Polynomial(new_variables)
    
    def __sub__(self, other):
        new_variables = defaultdict(int)
        for name in self.variables:
            new_variables[name] += self.variables[name]
        for name in other.variables:
            new_variables[name] -= other.variables[name]
        return Polynomial(new_variables)
    
    def __mul__(self, other):
        new_variables = defaultdict(int)
        for name in sorted(self.variables):
            for _name in sorted(other.variables):
                new_name = '*'.join(part for part in sorted(name.split('*') + _name.split('*')) if part)
                new_variables[new_name] += self.variables[name] * other.variables[_name]
        return Polynomial(new_variables)
    
    def to_list(self):
        result = []
        for name in sorted(self.variables, key=lambda x: (-len(x.split('*')), x)):
            if self.variables[name] != 0 and name != '':
                result.append(str(self.variables[name]) + '*' + name)
        if '' in self.variables and self.variables[''] != 0:
            result.append(str(self.variables['']))
        return result

    
class Parser:
    def __init__(self, variables):
        self.variables = dict(variables)
        self.tokens = deque()
    
    def evaluate(self, expression):
        self.tokens = deque([c for c in expression if c != ' '])
        return self._add()
        
    def _match(self, predicate):
        return self.tokens and predicate(self.tokens[0])
    
    def _consume(self, predicate):
        if self._match(predicate):
            return self.tokens.popleft()
        else:
            raise ValueError('Unexpected token')

    def _add(self):
        value = self._mult()
        while self._match(lambda x: x in {'+', '-'}):
            op = (lambda x, y: x+y) if self._consume(lambda x: True) == '+' else (lambda x, y: x-y)
            _value = self._mult()
            value = op(value, _value)
        return value

    def _mult(self):
        value = self._value()
        while self._match(lambda x: x in {'*'}):
            self._consume(lambda x: True)
            value = value * self._value()
        return value

    def _value(self):
        if self._match(lambda x: x.isalpha()): 
            buffer = []
            while self._match(lambda x: x.isalpha()):
                buffer.append(self._consume(lambda x: True))
            name = ''.join(buffer)
            if name in self.variables:
                return Polynomial({'': self.variables[name]})
            else:
                return Polynomial({name: 1})
        elif self._match(lambda x: x.isdigit()):
            buffer = [self._consume(lambda x: x.isdigit())]
            while self._match(lambda x: x.isdigit()):
                buffer.append(self._consume(lambda x: True))
            return Polynomial({'': int(''.join(buffer))})
        else:
            self._consume(lambda x: x == '(')
            value = self._add()
            self._consume(lambda x: x == ')')
            return value
    
class Solution:
    def basicCalculatorIV(self, expression, evalvars, evalints):
        parser = Parser({ evalvars[i]: evalints[i] for i in range(len(evalvars)) })

        result = parser.evaluate(expression)
        return result.to_list()
Scroll to Top