Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Basic Calculator

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "224" 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 a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). Example 1: Input: s = "1 + 1" Output: 2 Example 2: Input: s = " 2-1 + 2 " Output: 3 Example 3: Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23 Constraints: 1 <= s.length <= 3 * 105 s consists of digits, '+', '-', '(', ')', and ' '. s represents a valid expression. '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid). '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid). There will be no two consecutive operators in the input. Every number and running calculation will fit in a signed 32-bit integer.

Explanation

Here's a breakdown of the approach, followed by the Python code:

  • Iterative Processing with Stack: Process the string character by character. Use a stack to store the intermediate results and signs when encountering parentheses.
  • Sign Handling: Keep track of the current sign (+1 or -1) and update it when encountering '+' or '-'.
  • Parentheses Handling: When encountering '(', push the current result and sign onto the stack. When encountering ')', pop the previous sign and result from the stack to calculate the subexpression's value.

  • Runtime Complexity: O(n), where n is the length of the string s.

  • Storage Complexity: O(n) in the worst-case scenario where the expression has nested parentheses.

Code

    def calculate(s: str) -> int:
    """
    Evaluates a basic arithmetic expression string.

    Args:
        s: The expression string consisting of digits, '+', '-', '(', ')', and ' '.

    Returns:
        The result of the evaluation.
    """
    stack = []
    result = 0
    number = 0
    sign = 1  # 1 for positive, -1 for negative

    for char in s:
        if char.isdigit():
            number = number * 10 + int(char)
        elif char == '+':
            result += sign * number
            number = 0
            sign = 1
        elif char == '-':
            result += sign * number
            number = 0
            sign = -1
        elif char == '(':
            stack.append(result)
            stack.append(sign)
            result = 0
            sign = 1
        elif char == ')':
            result += sign * number
            number = 0
            result *= stack.pop()  # Pop the sign
            result += stack.pop()  # Pop the previous result

    if number != 0:
        result += sign * number

    return result

More from this blog

C

Chatmagic blog

2894 posts