Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Basic Calculator IV

Updated
5 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "770" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

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 ["-1a","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 "bac", only "abc". 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, "aabc" 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 ["-2aaa", "3aab", "3bb", "4a", "5c", "-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: ["-1a","14"] Example 2: Input: expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12] Output: ["-1pressure","5"] Example 3: Input: expression = "(e + 8) (e - 8)", evalvars = [], evalints = [] Output: ["1ee","-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

Explanation

Here's a breakdown of the solution:

  • Evaluate the Expression: Convert the expression string into a more manageable representation, then substitute any known variables using the evalvars and evalints mappings.
  • Polynomial Representation: Represent the simplified expression as a dictionary (or Counter) where keys are tuples of variable names (sorted lexicographically) and values are the corresponding coefficients.
  • Format the Output: Convert the polynomial representation into the desired string format, sorting by degree (highest first) and then lexicographically within each degree. Omit terms with zero coefficients.

  • Runtime Complexity: O(n log n), where n is the number of terms after expansion, primarily due to sorting.

  • Storage Complexity: O(n), where n is the number of terms after expansion, to store the polynomial representation.

Code

    from collections import defaultdict, Counter

class Solution:
    def basicCalculatorIV(self, expression: str, evalvars: list[str], evalints: list[int]) -> list[str]:
        """
        Evaluates a given expression with variable substitutions and simplifies it.

        Args:
            expression (str): The input expression string.
            evalvars (list[str]): List of variable names to be evaluated.
            evalints (list[int]): List of integer values corresponding to evalvars.

        Returns:
            list[str]: A list of strings representing the simplified expression.
        """

        eval_map = dict(zip(evalvars, evalints))

        def tokenize(s):
            tokens = []
            i = 0
            while i < len(s):
                if s[i] == ' ':
                    i += 1
                elif s[i].isalpha():
                    j = i
                    while j < len(s) and s[j].isalpha():
                        j += 1
                    tokens.append(s[i:j])
                    i = j
                elif s[i].isdigit():
                    j = i
                    while j < len(s) and s[j].isdigit():
                        j += 1
                    tokens.append(int(s[i:j]))
                    i = j
                else:
                    tokens.append(s[i])
                    i += 1
            return tokens

        tokens = tokenize(expression)

        def evaluate(tokens):
            def update(poly, other, op):
                new_poly = defaultdict(int)
                if op == '+':
                    for term, coeff in other.items():
                        new_poly[term] += coeff
                    for term, coeff in poly.items():
                        new_poly[term] += coeff
                elif op == '-':
                    for term, coeff in other.items():
                        new_poly[term] -= coeff
                    for term, coeff in poly.items():
                        new_poly[term] += coeff
                elif op == '*':
                    for term1, coeff1 in poly.items():
                        for term2, coeff2 in other.items():
                            new_term = tuple(sorted(term1 + term2))
                            new_poly[new_term] += coeff1 * coeff2
                return new_poly

            stack = []
            op = '+'
            i = 0
            while i < len(tokens):
                token = tokens[i]
                if token == '(':
                    j = i + 1
                    count = 1
                    while j < len(tokens) and count > 0:
                        if tokens[j] == '(':
                            count += 1
                        elif tokens[j] == ')':
                            count -= 1
                        j += 1
                    other = evaluate(tokens[i + 1:j - 1])
                    i = j
                elif isinstance(token, int):
                    other = {(): token}
                    i += 1
                elif isinstance(token, str):
                    if token in eval_map:
                        other = {(): eval_map[token]}
                    else:
                        other = {(token,): 1}
                    i += 1
                else:
                    stack.append(other)
                    op = token
                    i += 1
                    continue

                if not stack:
                    stack.append(other)
                else:
                    prev = stack.pop()
                    new = update(prev, other, op)
                    stack.append(new)
                    op = '+'

            return stack[0]

        poly = evaluate(tokens)

        result = []
        for term, coeff in poly.items():
            if coeff != 0:
                if not term:
                    result.append(str(coeff))
                else:
                    result.append(str(coeff) + "*" + "*".join(term))

        result.sort(key=lambda x: (-x.count('*'), tuple(x.split('*')[1:]) if '*' in x else ""), reverse=True)

        return result

More from this blog

C

Chatmagic blog

2894 posts