Python 0150.py
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
s = []
for t in tokens:
if t == "+":
sum = s[-2] + s[-1]
s.pop()
s.pop()
s.append(sum)
elif t == "-":
diff = s[-2] - s[-1]
s.pop()
s.pop()
s.append(diff)
elif t == "*":
mul = s[-2] * s[-1]
s.pop()
s.pop()
s.append(mul)
elif t == "/":
divi = int(s[-2] / s[-1]) # float-to-int => rounds towards zero
s.pop()
s.pop()
s.append(divi)
else:
s.append(int(t))
return s[0]
Difficulty
and has an acceptance rate of about 58% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Math
- Stack
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 implementation evaluates an expression written in Reverse Polish Notation (RPN) using a stack-based approach. It iterates through the token list, pushes numeric values onto a list that serves as a stack, and applies the four basic arithmetic operators when they appear. After processing all tokens, the sole remaining element on the stack is returned as the integer result.
Token Traversal
The core loop walks through each token in the input sequence.
for t in tokens:
...
During each iteration the code distinguishes between operators and operands. This linear traversal guarantees that every token is examined exactly once, preserving the order required by RPN evaluation.
Operand Handling
When a token is not one of the four operator symbols, it is interpreted as an integer literal and placed onto the stack.
else:
s.append(int(t))
The conversion to int ensures that subsequent arithmetic operations work with native integer types, and it also validates that the token represents a valid numeric value.
Operator Processing
Each operator triggers a pop-compute-push sequence. The implementation accesses the two most recent operands directly via negative indices, computes the result, removes the used operands, and pushes the new value back onto the stack.
Addition
if t == "+":
sum = s[-2] + s[-1]
s.pop()
s.pop()
s.append(sum)
The two topmost stack entries are summed, and the intermediate result replaces them.
Subtraction
elif t == "-":
diff = s[-2] - s[-1]
s.pop()
s.pop()
s.append(diff)
The order of operands respects RPN semantics: the second-to-top element is the minuend, and the top element is the subtrahend.
Multiplication
elif t == "*":
mul = s[-2] * s[-1]
s.pop()
s.pop()
s.append(mul)
Multiplication follows the same pop-compute-push pattern.
Division
elif t == "/":
divi = int(s[-2] / s[-1]) # float-to-int => rounds towards zero
s.pop()
s.pop()
s.append(divi)
Division is performed using true division, then cast to int. The cast truncates toward zero, matching the problem’s requirement for integer division that discards the fractional part regardless of sign. This handling automatically covers cases where the dividend or divisor is negative, ensuring the result follows the defined rounding rule.
Stack Management
The list s functions as a LIFO stack. Direct indexing (s[-2], s[-1]) provides immediate access to the operands without an explicit pop before the computation, which avoids an extra temporary variable. After the operation, two pop calls remove the consumed operands, and a single append inserts the computed value. This disciplined push-pop sequence maintains stack integrity throughout the evaluation.
Edge Cases Addressed
- Division by Zero: The algorithm assumes valid RPN input, and the division step will raise a runtime exception if the divisor is zero. The code’s structure inherently propagates this exception, aligning with typical expectations for invalid arithmetic expressions.
- Negative Numbers: Converting tokens with
int(t)correctly interprets negative literals. The subtraction and division sections preserve sign semantics by using the original operand order. - Single-Token Expressions: If the input consists of a solitary numeric token, the loop never enters any operator branch, and the final return statement yields that number directly.
- Large Intermediate Results: Python’s arbitrary-precision integers allow the stack to hold results that exceed conventional 32-bit limits without overflow, so the algorithm gracefully handles very large intermediate values.
Performance Optimizations
The solution operates in a single pass over the token list, eliminating the need for auxiliary data structures beyond the stack itself. Direct indexing (s[-2], s[-1]) avoids the overhead of repeatedly calling pop before the arithmetic operation, reducing the number of list mutations. The explicit pop calls after each computation remove only the two elements that are no longer needed, keeping the stack size minimal at any point. Casting the division result with int leverages Python’s built-in conversion, which is faster than implementing a custom truncation routine. Overall, the algorithm’s tight loop and minimal list operations contribute to efficient execution for inputs of any reasonable length.
Result Retrieval
After all tokens have been processed, the stack contains exactly one element-the final result. The method returns this value directly.
return s[0] ELI5 - Simplified Explanation
Imagine there is a big magical bucket where you keep your blocks. You have a list of instructions telling you what to do with these blocks.
When you see a number in the list, you pick it up and put it directly into the bucket. The bucket always holds onto the newest blocks right at the top.
When you see a plus sign, it means the bucket wants you to take the two blocks closest to the top, add them together to make a new, bigger block, and put that new block back into the bucket.
When you see a minus sign, you take the top two blocks, find out how much smaller one is than the other, and put that new difference block back into the bucket.
When you see a star, you take those top two blocks and multiply them together to make a new block, then drop that back inside.
When you see a slash, you take the top two blocks and share them out to see how many times one fits into the other, then put that result back into the bucket.
You keep doing this until you have gone through every single instruction in the list. By the end, there will be one final block left sitting inside the bucket.
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 | Rust | Java | C# | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| begeekmyfriend | C | ||||||||||||
| black-shadows | C++ | ||||||||||||
| bujosa | Rust | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| martianoff | Scala | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| bujosa | Rust | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| martianoff | Scala | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 224: Basic Calculator
- problem 282: Expression Add Operators
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
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