Problem 150

Abstract / Summary

Evaluate expressions given in postfix notation using a stack to compute the result step by step.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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]
28 lines | 814 bytes | submitted August 31, 2023 | GitHub   3% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Stack
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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]
written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.92 | σ = 1.17

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
56 links | 40 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Evaluate Reverse Polish Notation - Leetcode 150 - Python'
NeetCode 10 mins
Evaluate Reverse Polish Notation - Leetcode 150 - Python
YouTube video 'Evaluate Reverse Polish Notation | 2 Approaches | Leetcode 150'
codestorywithMIK 21 mins
Evaluate Reverse Polish Notation | 2 Approaches | Leetcode 150
YouTube video 'Evaluate Reverse Polish Notation (RPN) - Leetcode 150 - Stacks (Python)'
Greg Hogg 12 mins
Evaluate Reverse Polish Notation (RPN) - Leetcode 150 - Stacks (Python)
YouTube video 'Evaluate Reverse Polish Notation - LeetCode 150 - Python'
Deepti Talesra 12 mins
Evaluate Reverse Polish Notation - LeetCode 150 - Python
YouTube video 'Evaluate Reverse Polish Notation | Leetcode 150 | Stack'
Ayushi Sharma 5 mins
Evaluate Reverse Polish Notation | Leetcode 150 | Stack
YouTube video '150. Evaluate Reverse Polish Notation | Stack'
Aryan Mittal 17 mins
150. Evaluate Reverse Polish Notation | Stack
YouTube video 'Leetcode | 150. Evaluate Reverse Polish Notation | Medium | Java Solution'
Developer Docs 11 mins
Leetcode | 150. Evaluate Reverse Polish Notation | Medium | Java Solution
YouTube video 'Evaluate Reverse Polish Notation | Leetcode 150 | Live coding session'
Coding Decoded 9 mins
Evaluate Reverse Polish Notation | Leetcode 150 | Live coding session
YouTube video 'Evaluate Reverse Polish Notation | Leetcode 150 | Stack | Google Amazon | Java Python'
Naresh Gupta 10 mins
Evaluate Reverse Polish Notation | Leetcode 150 | Stack | Google Amazon | Java Python
YouTube video 'Evaluate Reverse Polish Notation - LeetCode 150 - Stack Data Structure'
AlgosWithMichael 12 mins
Evaluate Reverse Polish Notation - LeetCode 150 - Stack Data Structure
YouTube video 'Leetcode 150 Evaluate Reverse Polish Notation (Java)'
TheAnalyticGuy 7 mins
Leetcode 150 Evaluate Reverse Polish Notation (Java)
YouTube video 'EVALUATE REVERSE POLISH NOTATION | LEETCODE # 150 | PYTHON STACK SOLUTION'
Cracking FAANG 14 mins
EVALUATE REVERSE POLISH NOTATION | LEETCODE # 150 | PYTHON STACK SOLUTION
YouTube video 'LeetCode 150: Evaluate Reverse Polish Notation Explained | Stack Approach | srkcodes'
Srk Codes 13 mins
LeetCode 150: Evaluate Reverse Polish Notation Explained | Stack Approach | srkcodes
YouTube video '✅ Evaluate Reverse Polish Notation - LeetCode 150 - Stack - Arrays - Strings - Explained in Detail'
Leet Logics 12 mins
✅ Evaluate Reverse Polish Notation - LeetCode 150 - Stack - Arrays - Strings - Explained in Detail
YouTube video '150. Evaluate Reverse Polish Notation | Leetcode | Stack | DSA'
Coding with Tamilarasan 9 mins
150. Evaluate Reverse Polish Notation | Leetcode | Stack | DSA
YouTube video '150. Evaluate Reverse Polish Notation | JavaScript | LeetCode Daily Challenge | Stack | Easy  Simple'
LeetCodeWithMonu 15 mins
150. Evaluate Reverse Polish Notation | JavaScript | LeetCode Daily Challenge | Stack | Easy Simple
YouTube video 'Evaluate Reverse Polish Notation - LeetCode #150 - C++'
Sean Chuah 4 mins
Evaluate Reverse Polish Notation - LeetCode #150 - C++
YouTube video 'Evaluate Reverse Polish Notation | LeetCode 150 | Coders Camp'
Coders Camp 7 mins
Evaluate Reverse Polish Notation | LeetCode 150 | Coders Camp
YouTube video '150. Evaluate Reverse Polish Notation || NEETCODE 150'
TechWithSaumya 9 mins
150. Evaluate Reverse Polish Notation || NEETCODE 150
YouTube video '150 || Evaluate Reverse Polish Notation || Leetcode Daily Challenge'
CodeFreaks 9 mins
150 || Evaluate Reverse Polish Notation || Leetcode Daily Challenge
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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