Solving Leetcode Interviews in Seconds with AI: Basic Calculator II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "227" 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 which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). Example 1: Input: s = "3+22" Output: 7 Example 2: Input: s = " 3/2 " Output: 1 Example 3: Input: s = " 3+5 / 2 " Output: 5 Constraints: 1 <= s.length <= 3 105 s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces. s represents a valid expression. All the integers in the expression are non-negative integers in the range [0, 231 - 1]. The answer is guaranteed to fit in a 32-bit integer.
Explanation
Here's a solution to evaluate a string expression, addressing efficiency and optimality.
- Iterative Processing with Stack: The solution iterates through the input string
s, maintaining a stack to store intermediate results. This avoids recursion and allows for efficient processing of operators based on precedence. - Handling Operators: When an operator (+, -, *, /) is encountered, the top element of the stack is combined with the current number based on the previous operator. Multiplication and division are performed immediately to ensure precedence.
Final Summation: After processing the entire string, the stack contains the final values to be summed up to produce the result.
Runtime Complexity: O(n), where n is the length of the string
s.- Storage Complexity: O(n) in the worst case, where n is the length of the string
s(e.g., a string with only additions and subtractions).
Code
def calculate(s: str) -> int:
stack = []
num = 0
op = '+'
s += '+0' # Append a dummy operation to flush the last number
for char in s:
if char.isdigit():
num = num * 10 + int(char)
elif char in '+-*/':
if op == '+':
stack.append(num)
elif op == '-':
stack.append(-num)
elif op == '*':
stack.append(stack.pop() * num)
else:
stack.append(int(stack.pop() / num)) # Integer division
num = 0
op = char
elif char == ' ':
continue
return sum(stack)