KatInterview

781. Basic Calculator IV

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to evaluate a mathematical expression containing integers, variables, addition, subtraction, multiplication, and parentheses. Some variables have assigned values, while others are free. The final result should be a simplified polynomial, represented as a list of strings, with terms formatted and sorted according to specific rules. This is fundamentally a symbolic algebra problem, requiring us to manage polynomials rather than just calculating a single numerical value.

Solution

Basic Calculator IV in Python

from collections import Counter

class Poly:
    def __init__(self, expr=None):
        # self.terms maps a tuple of variables to its coefficient.
        # e.g., '2*a*b' is represented as {('a', 'b'): 2}.
        # A constant term is represented by an empty tuple: {(): 2}.
        self.terms = Counter()
        if isinstance(expr, int):
            if expr != 0:
                self.terms[()] = expr
        elif isinstance(expr, str):
            self.terms[(expr,)] = 1

    def add(self, other):
        res = Poly()
        res.terms = self.terms + other.terms
        return res

    def sub(self, other):
        res = Poly()
        res.terms = self.terms - other.terms
        return res

    def mul(self, other):
        res = Poly()
        for term1, coeff1 in self.terms.items():
            for term2, coeff2 in other.terms.items():
                new_term = tuple(sorted(term1 + term2))
                res.terms[new_term] += coeff1 * coeff2
        return res

    def to_list(self):
        # Filter out terms with zero coefficients.
        filtered_terms = sorted([item for item in self.terms.items() if item[1] != 0],
                              key=lambda x: (-len(x[0]), x[0]))

        result = []
        for term, coeff in filtered_terms:
            if not term:
                result.append(str(coeff))
            else:
                result.append(f"{coeff}*{'*'.join(term)}")
        return result

class Solution:
    def basicCalculatorIV(self, expression: str, evalvars: list[str], evalints: list[int]) -> list[str]:
        eval_map = {var: val for var, val in zip(evalvars, evalints)}

        values = []
        ops = []

        def precedence(op):
            if op in ('+', '-'): return 1
            if op == '*': return 2
            return 0  # For parentheses

        def apply_op():
            op = ops.pop()
            right = values.pop()
            left = values.pop()
            if op == '+':
                values.append(left.add(right))
            elif op == '-':
                values.append(left.sub(right))
            elif op == '*':
                values.append(left.mul(right))

        tokens = expression.split(' ')
        for token in tokens:
            if token.isdigit():
                values.append(Poly(int(token)))
            elif token.isalpha():
                if token in eval_map:
                    values.append(Poly(eval_map[token]))
                else:
                    values.append(Poly(token))
            elif token == '(':
                ops.append(token)
            elif token == ')':
                while ops and ops[-1] != '(':
                    apply_op()
                ops.pop()  # Pop '('
            else:  # Operator
                while ops and ops[-1] != '(' and precedence(ops[-1]) >= precedence(token):
                    apply_op()
                ops.append(token)

        while ops:
            apply_op()

        if not values:
            return []
            
        return values[0].to_list()

Basic Calculator IV in Java

class Solution {
    // Inner class to represent a polynomial.
    class Poly {
        // A map from a term to its coefficient.
        // A term is represented by a sorted list of its variable factors.
        // e.g., for term "-2*a*b*b", the key is ["a","b","b"] and value is -2.
        // A constant term like 5 has an empty list as key and 5 as value.
        Map<List<String>, Integer> terms = new HashMap<>();

        // Constructor for a constant value.
        Poly(int val) {
            if (val != 0) {
                terms.put(new ArrayList<>(), val);
            }
        }

        // Constructor for a single variable.
        Poly(String var) {
            List<String> term = new ArrayList<>();
            term.add(var);
            terms.put(term, 1);
        }

        // Default constructor for creating an empty polynomial.
        Poly() {}

        // Addition: returns a new polynomial that is the sum of this and other.
        Poly add(Poly other) {
            Poly result = new Poly();
            // Add terms from this polynomial
            for (Map.Entry<List<String>, Integer> entry : this.terms.entrySet()) {
                result.terms.put(new ArrayList<>(entry.getKey()), entry.getValue());
            }
            // Add terms from other polynomial
            for (Map.Entry<List<String>, Integer> entry : other.terms.entrySet()) {
                result.terms.put(entry.getKey(), result.terms.getOrDefault(entry.getKey(), 0) + entry.getValue());
            }
            return result;
        }

        // Subtraction: returns a new polynomial.
        Poly sub(Poly other) {
            Poly result = new Poly();
            for (Map.Entry<List<String>, Integer> entry : this.terms.entrySet()) {
                result.terms.put(new ArrayList<>(entry.getKey()), entry.getValue());
            }
            for (Map.Entry<List<String>, Integer> entry : other.terms.entrySet()) {
                result.terms.put(entry.getKey(), result.terms.getOrDefault(entry.getKey(), 0) - entry.getValue());
            }
            return result;
        }

        // Multiplication: returns a new polynomial.
        Poly mul(Poly other) {
            Poly result = new Poly();
            for (Map.Entry<List<String>, Integer> entry1 : this.terms.entrySet()) {
                for (Map.Entry<List<String>, Integer> entry2 : other.terms.entrySet()) {
                    List<String> newTerm = new ArrayList<>(entry1.getKey());
                    newTerm.addAll(entry2.getKey());
                    Collections.sort(newTerm);
                    int newCoeff = entry1.getValue() * entry2.getValue();
                    result.terms.put(newTerm, result.terms.getOrDefault(newTerm, 0) + newCoeff);
                }
            }
            return result;
        }

        // Converts the polynomial to the required list of strings.
        List<String> toList() {
            List<Map.Entry<List<String>, Integer>> sortedTerms = new ArrayList<>();
            for (Map.Entry<List<String>, Integer> entry : terms.entrySet()) {
                if (entry.getValue() != 0) {
                    sortedTerms.add(entry);
                }
            }

            // Sort by degree descending, then lexicographically.
            sortedTerms.sort((a, b) -> {
                if (a.getKey().size() != b.getKey().size()) {
                    return b.getKey().size() - a.getKey().size();
                }
                for (int i = 0; i < a.getKey().size(); i++) {
                    int cmp = a.getKey().get(i).compareTo(b.getKey().get(i));
                    if (cmp != 0) return cmp;
                }
                return 0;
            });

            List<String> result = new ArrayList<>();
            for (Map.Entry<List<String>, Integer> entry : sortedTerms) {
                StringBuilder sb = new StringBuilder();
                sb.append(entry.getValue());
                if (!entry.getKey().isEmpty()) {
                    sb.append("*");
                    sb.append(String.join("*", entry.getKey()));
                }
                result.add(sb.toString());
            }
            return result;
        }
    }

    public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
        Map<String, Integer> evalMap = new HashMap<>();
        for (int i = 0; i < evalvars.length; i++) {
            evalMap.put(evalvars[i], evalints[i]);
        }

        Stack<Poly> values = new Stack<>();
        Stack<Character> ops = new Stack<>();
        String[] tokens = expression.split(" ");

        for (String token : tokens) {
            char firstChar = token.charAt(0);
            if (Character.isDigit(firstChar) || (firstChar == '-' && token.length() > 1)) {
                values.push(new Poly(Integer.parseInt(token)));
            } else if (Character.isLetter(firstChar)) {
                if (evalMap.containsKey(token)) {
                    values.push(new Poly(evalMap.get(token)));
                } else {
                    values.push(new Poly(token));
                }
            } else if (firstChar == '(') {
                ops.push(firstChar);
            } else if (firstChar == ')') {
                while (!ops.isEmpty() && ops.peek() != '(') {
                    applyOp(values, ops);
                }
                ops.pop(); // Pop '('
            } else { // Operator
                while (!ops.isEmpty() && ops.peek() != '(' && precedence(ops.peek()) >= precedence(firstChar)) {
                    applyOp(values, ops);
                }
                ops.push(firstChar);
            }
        }

        while (!ops.isEmpty()) {
            applyOp(values, ops);
        }

        return values.pop().toList();
    }

    private void applyOp(Stack<Poly> values, Stack<Character> ops) {
        char op = ops.pop();
        Poly right = values.pop();
        Poly left = values.pop();
        if (op == '+') values.push(left.add(right));
        else if (op == '-') values.push(left.sub(right));
        else if (op == '*') values.push(left.mul(right));
    }

    private int precedence(char op) {
        if (op == '+' || op == '-') return 1;
        if (op == '*') return 2;
        return 0; // for parentheses
    }
}

Basic Calculator IV in C++

class Solution {
private:
    // A struct to represent a polynomial term and its coefficient.
    // Using a map from a sorted vector of variables to an integer coefficient.
    struct Poly {
        map<vector<string>, int> terms;

        // Constructor for a constant value.
        Poly(int val) {
            if (val != 0) {
                terms[{}] = val;
            }
        }

        // Constructor for a single variable.
        Poly(const string& var) {
            terms[{{var}}] = 1;
        }

        // Default constructor.
        Poly() {}

        // Addition of two polynomials.
        Poly add(const Poly& other) const {
            Poly result = *this;
            for (auto const& [term, coeff] : other.terms) {
                result.terms[term] += coeff;
            }
            return result;
        }

        // Subtraction of two polynomials.
        Poly sub(const Poly& other) const {
            Poly result = *this;
            for (auto const& [term, coeff] : other.terms) {
                result.terms[term] -= coeff;
            }
            return result;
        }

        // Multiplication of two polynomials.
        Poly mul(const Poly& other) const {
            Poly result;
            for (auto const& [term1, coeff1] : terms) {
                for (auto const& [term2, coeff2] : other.terms) {
                    vector<string> new_term = term1;
                    new_term.insert(new_term.end(), term2.begin(), term2.end());
                    sort(new_term.begin(), new_term.end());
                    result.terms[new_term] += coeff1 * coeff2;
                }
            }
            return result;
        }

        // Convert the polynomial to the required list of strings.
        vector<string> to_list() {
            vector<pair<vector<string>, int>> sorted_terms;
            for (auto const& [term, coeff] : terms) {
                if (coeff != 0) {
                    sorted_terms.push_back({term, coeff});
                }
            }

            // Sort terms: by degree descending, then lexicographically.
            sort(sorted_terms.begin(), sorted_terms.end(), [](const auto& a, const auto& b) {
                if (a.first.size() != b.first.size()) {
                    return a.first.size() > b.first.size();
                }
                return a.first < b.first;
            });

            vector<string> result;
            for (const auto& [term, coeff] : sorted_terms) {
                string term_str = to_string(coeff);
                for (const auto& var : term) {
                    term_str += "*" + var;
                }
                result.push_back(term_str);
            }
            return result;
        }
    };

    int precedence(char op) {
        if (op == '+' || op == '-') return 1;
        if (op == '*') return 2;
        return 0; // For parentheses
    }

    void applyOp(stack<Poly>& values, stack<char>& ops) {
        char op = ops.top();
        ops.pop();
        Poly right = values.top();
        values.pop();
        Poly left = values.top();
        values.pop();
        if (op == '+') values.push(left.add(right));
        else if (op == '-') values.push(left.sub(right));
        else if (op == '*') values.push(left.mul(right));
    }

public:
    vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {
        unordered_map<string, int> evalMap;
        for (int i = 0; i < evalvars.size(); ++i) {
            evalMap[evalvars[i]] = evalints[i];
        }

        stack<Poly> values;
        stack<char> ops;

        stringstream ss(expression);
        string token;
        while (ss >> token) {
            if (isdigit(token[0]) || (token[0] == '-' && token.length() > 1)) {
                values.push(Poly(stoi(token)));
            } else if (isalpha(token[0])) {
                if (evalMap.count(token)) {
                    values.push(Poly(evalMap[token]));
                } else {
                    values.push(Poly(token));
                }
            } else if (token[0] == '(') {
                ops.push('(');
            } else if (token[0] == ')') {
                while (!ops.empty() && ops.top() != '(') {
                    applyOp(values, ops);
                }
                ops.pop(); // Pop '('
            } else { // Operator
                while (!ops.empty() && ops.top() != '(' && precedence(ops.top()) >= precedence(token[0])) {
                    applyOp(values, ops);
                }
                ops.push(token[0]);
            }
        }

        while (!ops.empty()) {
            applyOp(values, ops);
        }

        return values.top().to_list();
    }
};

Basic Calculator IV in TypeScript

class Poly {
    // Map from a stringified canonical term to its coefficient.
    // e.g., {"a*b": 2} for 2*a*b. Constant term uses empty string "": 5
    terms: Map<string, number>;

    constructor(expr?: number | string) {
        this.terms = new Map();
        if (typeof expr === 'number' && expr !== 0) {
            this.terms.set("", expr);
        } else if (typeof expr === 'string') {
            this.terms.set(expr, 1);
        }
    }

    add(other: Poly): Poly {
        const res = new Poly();
        this.terms.forEach((coeff, term) => res.terms.set(term, coeff));
        other.terms.forEach((coeff, term) => {
            res.terms.set(term, (res.terms.get(term) || 0) + coeff);
        });
        return res;
    }

    sub(other: Poly): Poly {
        const res = new Poly();
        this.terms.forEach((coeff, term) => res.terms.set(term, coeff));
        other.terms.forEach((coeff, term) => {
            res.terms.set(term, (res.terms.get(term) || 0) - coeff);
        });
        return res;
    }

    mul(other: Poly): Poly {
        const res = new Poly();
        this.terms.forEach((c1, t1) => {
            other.terms.forEach((c2, t2) => {
                const newCoeff = c1 * c2;
                const v1 = t1 === "" ? [] : t1.split('*');
                const v2 = t2 === "" ? [] : t2.split('*');
                const newVars = [...v1, ...v2].sort();
                const newKey = newVars.join('*');

                res.terms.set(newKey, (res.terms.get(newKey) || 0) + newCoeff);
            });
        });
        return res;
    }

    toList(): string[] {
        const filtered: [string, number][] = [];
        this.terms.forEach((coeff, term) => {
            if (coeff !== 0) {
                filtered.push([term, coeff]);
            }
        });

        filtered.sort(([t1], [t2]) => {
            const v1 = t1 === "" ? [] : t1.split('*');
            const v2 = t2 === "" ? [] : t2.split('*');
            if (v1.length !== v2.length) {
                return v2.length - v1.length;
            }
            return t1 < t2 ? -1 : (t1 > t2 ? 1 : 0);
        });

        return filtered.map(([term, coeff]) => {
            if (term === "") return String(coeff);
            return `${coeff}*${term}`;
        });
    }
}

function basicCalculatorIV(expression: string, evalvars: string[], evalints: number[]): string[] {
    const evalMap = new Map<string, number>();
    for (let i = 0; i < evalvars.length; i++) {
        evalMap.set(evalvars[i], evalints[i]);
    }

    const values: Poly[] = [];
    const ops: string[] = [];

    const precedence = (op: string): number => {
        if (op === '+' || op === '-') return 1;
        if (op === '*') return 2;
        return 0; // For parentheses
    };

    const applyOp = () => {
        const op = ops.pop()!;
        const right = values.pop()!;
        const left = values.pop()!;
        if (op === '+') values.push(left.add(right));
        else if (op === '-') values.push(left.sub(right));
        else if (op === '*') values.push(left.mul(right));
    };

    const tokens = expression.split(' ');
    for (const token of tokens) {
        const num = parseInt(token);
        if (!isNaN(num) && String(num) === token) {
            values.push(new Poly(num));
        } else if (token === '(') {
            ops.push(token);
        } else if (token === ')') {
            while (ops.length > 0 && ops[ops.length - 1] !== '(') {
                applyOp();
            }
            ops.pop(); // Pop '('
        } else if (['+', '-', '*'].includes(token)) {
            while (ops.length > 0 && ops[ops.length - 1] !== '(' && precedence(ops[ops.length - 1]) >= precedence(token)) {
                applyOp();
            }
            ops.push(token);
        } else { // Variable
            if (evalMap.has(token)) {
                values.push(new Poly(evalMap.get(token)!));
            } else {
                values.push(new Poly(token));
            }
        }
    }

    while (ops.length > 0) {
        applyOp();
    }

    if (values.length === 0) return [];
    return values[0].toList();
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.