Python 0227.py
class Solution:
def calculate(self, s: str) -> int:
s = s.replace(" ", "") # discard spaces
s += "?" # end-marker
op = "+"
num = 0
todo = []
# no brackets, almost sequential evaluation possible
# note: * and / have hive precedence than + and -
for c in s:
if c.isnumeric():
num = 10 * num + int(c)
else:
if op == "+":
todo.append(+num)
elif op == "-":
todo.append(-num)
elif op == "*":
last = todo.pop()
todo.append(last * num)
elif op == "/":
last = todo.pop()
div = last // num
if div < 0:
div = -(abs(last) // abs(num))
todo.append(div)
op = c
num = 0
if c == "?": # done
return sum(todo)
Difficulty
and has an acceptance rate of about 47% (2+ million submissions).
Typical patterns to solve this problem:
- Math
- Stack
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation evaluates a mathematical expression given as a string containing non-negative integers and the operators +, -, *, and /. It first removes whitespace, appends a sentinel character to simplify termination, and then walks through the characters once, building intermediate results in a list. The final answer is obtained by summing the list. The algorithm respects the usual precedence rules where multiplication and division are performed before addition and subtraction, without using explicit recursion or a stack of operators.
Key Steps
The core of the solution can be divided into three conceptual phases: preprocessing, token processing, and final aggregation.
Preprocessing
s = s.replace(" ", "") # discard spaces
s += "?" # end-marker
All spaces are stripped to guarantee that only meaningful characters remain. Adding a sentinel ? ensures that the last number is processed without requiring a separate post-loop block.
Token Processing Loop
op = "+"
num = 0
todo = []
for c in s:
if c.isnumeric():
num = 10 * num + int(c)
else:
if op == "+":
todo.append(+num)
elif op == "-":
todo.append(-num)
elif op == "*":
last = todo.pop()
todo.append(last * num)
elif op == "/":
last = todo.pop()
div = last // num
if div < 0:
div = -(abs(last) // abs(num))
todo.append(div)
op = c
num = 0
if c == "?": # done
return sum(todo)
The loop iterates over each character. When a digit is encountered, it contributes to the current number num using base-10 accumulation. Encountering a non-digit triggers the handling of the previously seen operator stored in op. The handling logic distinguishes four cases:
- For
+the positive value ofnumis appended. - For
-the negative value ofnumis appended. - For
*the most recent entry intodois removed, multiplied bynum, and the product is pushed back. - For
/the most recent entry is removed, integer-divided bynum, and the quotient is pushed back. A correction step ensures that division truncates toward zero, matching the behavior of typical calculators.
After processing, op is updated to the current character and num is reset, preparing for the next number.
Final Aggregation
The sentinel ? causes an immediate return of the sum of all entries in todo. Because multiplication and division have already been folded into the list, the sum operation yields the correct result respecting operator precedence.
Edge Cases Handled
The code gracefully manages several subtle situations:
- Multi-digit numbers - The accumulation
num = 10 * num + int(c)correctly builds numbers of arbitrary length without overflow concerns in Python. - Trailing operator - The sentinel
?forces the final pending operation to be applied, eliminating the need for special end-of-string checks. - Division of negative numbers - Pythonβs floor division (
//) rounds toward negative infinity. The additional conditional block detects a negative quotient and recomputes the division using absolute values, then re-applies the sign. This reproduces truncation toward zero, which is the expected behavior for integer division in many programming problems. - Consecutive operators without spaces - Because the loop processes an operator only after a number has been fully read, sequences like
3+-2are interpreted correctly:+processes3, then-becomes the next operator for2. - Empty or whitespace-only input - After stripping spaces, an empty string becomes just the sentinel
?. The loop immediately returnssum([]), which is0, a sensible default for an empty expression.
Performance Optimizations
The implementation exhibits several efficiency-focused choices:
- Single pass traversal - By iterating once over the augmented string, the algorithm avoids multiple scans or recursive descent, keeping the runtime proportional to the length of the input.
- In-place number construction - Accumulating digits into
numavoids creating intermediate substring objects, reducing memory churn. - Use of a list as a lightweight stack - The
todolist serves both as a container for pending addition/subtraction terms and as a stack for the most recent operand needed by*and/. Listappendandpopoperations are amortized O(1), providing fast updates. - Early termination with sentinel - The sentinel character eliminates the need for a separate finalization step after the loop, allowing the function to return as soon as the sentinel is encountered.
- Avoidance of explicit operator precedence tables - By handling multiplication and division immediately when they appear, the code sidesteps the overhead of shunting-yard algorithms or expression trees, while still respecting precedence.
Overall, the solution delivers a concise, linear-time evaluation of arithmetic expressions with correct handling of integer division semantics and minimal auxiliary data structures.
ELI5 - Simplified Explanation
Imagine this code is like a little robot chef helping you solve a math puzzle. First, the robot cleans up the puzzle by taking away any empty spaces so it can see the numbers clearly. It puts a special mark at the end to know when it is finished working.
The robot keeps a list to hold pieces of the math problem. It walks through the symbols one by one. When it finds a number, it builds it up digit by digit. Whenever the robot hits a plus or minus or multiplication or division sign, it decides what to do with that number.
If it sees a plus sign, it saves the number in the list to be added later. If it sees a minus sign, it makes the number small and negative before saving it. If the robot sees multiplication or division, it realizes it needs to do some work right away. It takes the last number it saved out of its list, changes it by the new number, and puts the result back in.
Finally, when the robot hits that special mark at the end, it adds everything in its list together to tell you the final answer.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | C# | Go | ||||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| martianoff | Scala | ||||||||||||
| ruoru | Rust | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, C#, Go, Java, Python | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| martianoff | Scala | ||||||||||||
| ruoru | Rust | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 224: Basic Calculator
Solved On The Same Day
- problem 401: Binary Watch
- problem 241: Different Ways to Add Parentheses
- problem 284: Peeking Iterator
- problem 299: Bulls and Cows
- problem 365: Water and Jug Problem
- problem 375: Guess Number Higher or Lower II
- problem 376: Wiggle Subsequence
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality