Python 0224.py
class Solution:
# see problem 227
def calculate(self, s: str) -> int:
s = s.replace(" ", "") # discard spaces
s += "?" # end-marker
num = 0
sum = 0
minus = False
negate = [ minus ]
# 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)
elif c == "(":
negate.append(minus)
elif c == ")":
negate.pop()
else: # "+", "-", "?"
sum += -num if minus else +num
num = 0
minus = (c == "-")
if negate[-1] == True:
minus = not minus
return sum
Difficulty
and has an acceptance rate of about 47% (1+ million submissions).
Typical patterns to solve this problem:
- Math
- Recursion
- 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 an arithmetic expression containing the operators + and -, integer operands, and parentheses. It first removes whitespace, appends a sentinel character to guarantee that the last number is folded into the running total, and then walks through the characters exactly once. A small stack records the sign context introduced by each opening parenthesis, allowing the algorithm to correctly propagate negations through nested groups without building an explicit abstract syntax tree.
Key Steps
Preprocessing and Sentinel Insertion
s = s.replace(" ", "") # discard spaces
s += "?" # end-marker
All spaces are stripped so that the parser can treat every remaining character as meaningful. Adding a non-operator sentinel (?) forces the final pending number to be added to the cumulative sum when the loop reaches the end of the original input.
Variable Initialization
num = 0
sum = 0
minus = False
negate = [ minus ]
num accumulates the current multi-digit integer. sum holds the running total. minus records whether the next number should be subtracted. negate is a stack (implemented as a Python list) that stores the sign context at each level of parentheses; the initial context reflects the outermost (non-parenthesized) level.
Main Scan Loop
for c in s:
if c.isnumeric():
num = 10 * num + int(c)
elif c == "(":
negate.append(minus)
elif c == ")":
negate.pop()
else: # "+", "-", "?"
sum += -num if minus else +num
num = 0
minus = (c == "-")
if negate[-1] == True:
minus = not minus
The loop distinguishes four categories of characters:
- Digits - they are folded into
numusing base-10 multiplication, enabling the parser to handle numbers of arbitrary length without additional conversion steps. - Opening parenthesis - the current
minusflag is pushed ontonegate. This captures the sign that should affect the entire sub-expression inside the new pair of parentheses. - Closing parenthesis - the most recent sign context is popped, restoring the sign that applies after the closed group.
- Operators or sentinel - the accumulated
numis folded intosumwith the appropriate sign. The sign for the next number (minus) is set based on whether the current operator is-. If the surrounding parentheses have introduced a negation (negate[-1]isTrue), the sign is flipped, correctly handling expressions such as-(a-b).
Final Result
return sum
After the sentinel forces the last addition, sum contains the evaluated integer value of the entire expression.
Edge Cases Handled
The algorithm gracefully processes inputs that contain leading or trailing spaces because all whitespace is removed before parsing. Empty strings become just the sentinel, causing the loop to add zero and return 0. Consecutive operators are not expected by the problem definition, but the sentinel ensures that a trailing number is never omitted. Nested parentheses of any depth are supported: each opening parenthesis pushes the current sign context, and each closing parenthesis restores it, guaranteeing correct sign propagation through arbitrarily deep nesting. Multi-digit numbers are assembled digit by digit, so numbers like 12345 are handled without overflow concerns in Python’s arbitrary-precision integers.
Performance Optimizations
The solution performs a single linear pass over the input string, avoiding any recursive descent or secondary tokenization phases. By using a simple integer accumulator (num) and updating the total (sum) only when an operator or the sentinel is encountered, the code minimizes the number of arithmetic operations. The sign-context stack (negate) grows only with the nesting depth of parentheses, which in typical use cases is far smaller than the length of the expression, keeping auxiliary memory usage low. The sentinel character eliminates the need for a post-loop cleanup step, allowing the loop body to remain uniform for all characters and thus benefiting from branch prediction in modern CPUs.
ELI5 - Simplified Explanation
Imagine this computer code is like a little robot helper designed to solve math problems written in a long row. The robot starts by cleaning up the math problem to make sure there are no messy spaces in the way, and it adds a special secret marker at the end so it knows exactly when to stop working.
There are a few helper spots in the robot's memory. One spot keeps track of the number currently being built, one spot keeps track of the total sum, and another spot remembers if it needs to subtract rather than add. The robot walks through every character of the math problem one by one. If it sees a digit like one or five, it turns that into a number and pushes it into the memory spot for the current number.
When the robot finds a plus or a minus sign, it knows the time has come to add the current number it held onto the total sum. After that, it empties its memory spot so it can start building the next number. The robot continues this process, picking up numbers and signs, until it hits that secret marker at the end which tells it that the math problem is all finished and the total is ready.
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++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | C# | Python | Go | TS | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| martianoff | Scala | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | |||||||||||
| 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 | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| martianoff | Scala | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin |
Videos
Similar Problems
- problem 150: Evaluate Reverse Polish Notation
- problem 227: Basic Calculator II
- problem 241: Different Ways to Add Parentheses
- problem 282: Expression Add Operators
- problem 772: Basic Calculator III
- problem 2019: The Score of Students Solving Math Expression
- problem 2232: Minimize Result by Adding Parentheses to Expression
Solved On The Same Day
- problem 520: Detect Capital
- problem 316: Remove Duplicate Letters
- problem 690: Employee Importance
- problem 909: Snakes and Ladders
- problem 918: Maximum Sum Circular Subarray
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