Basic Calculator II - Complete Solution Guide
Basic Calculator II is LeetCode problem 227, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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 [-2 31 , 2 31 - 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+2*2" Output: 7 Example 2: Input: s = " 3/2 " Output: 1 Example 3: Input: s
Detailed Explanation
The problem asks us to implement a basic calculator that can evaluate a string expression containing non-negative integers and the operators +, -, *, and /. The integer division should truncate towards zero. We are not allowed to use built-in functions like `eval()`. The expression is guaranteed to be valid, and intermediate results will be within the range of a 32-bit integer.
Solution Approach
The solution iterates through the input string `s`. It maintains a `current_number` and an `operator`. When a digit is encountered, it's used to build the current number. When an operator or the end of the string is reached, the `current_number` is processed based on the last encountered `operator`. If the operator is `+` or `-`, the `current_number` (or its negation) is pushed onto the stack. If the operator is `*` or `/`, the top element of the stack is popped, the corresponding operation is performed with `current_number`, and the result is pushed back onto the stack. Finally, the sum of all elements in the stack is returned.
Step-by-Step Algorithm
- Step 1: Initialize an empty stack, `current_number` to 0, and `operator` to '+'.
- Step 2: Iterate through the input string `s`.
- Step 3: If the current character is a digit, update `current_number` by multiplying it by 10 and adding the digit.
- Step 4: If the current character is an operator or it is the end of the string, process the `current_number` based on the `operator`:
- Step 5: If `operator` is '+', push `current_number` onto the stack.
- Step 6: If `operator` is '-', push `-current_number` onto the stack.
- Step 7: If `operator` is '*', pop the top element from the stack, multiply it by `current_number`, and push the result back onto the stack.
- Step 8: If `operator` is '/', pop the top element from the stack, divide it by `current_number` (integer division), and push the result back onto the stack.
- Step 9: Update `operator` to the current character and reset `current_number` to 0.
- Step 10: After iterating through the entire string, sum up all the elements in the stack and return the result.
Key Insights
- Insight 1: The key insight is that we can handle multiplication and division immediately as we encounter them, due to their higher precedence. Addition and subtraction can be handled later.
- Insight 2: Using a stack helps to store the intermediate results and operators. Specifically, we can push numbers onto the stack based on the current operator, and then sum the stack at the end.
- Insight 3: We need to handle spaces properly and consider the last character of the string when it's a digit.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: Math, String, Stack.
Companies
Asked at: Accenture, Airbnb, Anduril, ByteDance, Coupang, DE Shaw, DoorDash, Google, Highspot, IXL, NetApp, Rokt, ServiceNow, Snap, Snowflake, Tesla, The Trade Desk, Verkada, Zoho, Zoox.