150. Evaluate Reverse Polish Notation
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Stack
- Time
- O(N)
- Space
- O(N)
Standard Solution (C++)
SummaryGiven a list of tokens representing a mathematical expression in Reverse Polish Notation, compute and return the integer result, where division truncates toward zero.
Approach
- Use a single stack of integers: push operands, and on each operator pop the top two values, apply the operation, then push the result.
- The key insight is that RPN guarantees operands always appear before the operator that consumes them, so a left-to-right pass with a stack is both correct and sufficient.
- Pop in order — the second-popped value is always the left operand, so
b op apreserves the original expression semantics. - After processing all tokens exactly one value remains on the stack: the final answer.
#include <vector>
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (const string& tok : tokens) {
if (tok == "+" || tok == "-" || tok == "*" || tok == "/") {
int rhs = st.top(); st.pop();
int lhs = st.top(); st.pop();
if (tok == "+") st.push(lhs + rhs);
else if (tok == "-") st.push(lhs - rhs);
else if (tok == "*") st.push(lhs * rhs);
else st.push(lhs / rhs); // truncates toward zero in C++11+
} else {
// Operand (integer, possibly negative)
st.push(stoi(tok));
}
}
return st.top();
}
};
Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
std::stack<int> st;
for(const string& t: tokens){
if(t=="+"){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(b+a);
}
else if(t=="-"){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(b-a);
}
else if(t=="*"){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(b*a);
}
else if(t=="/"){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(b/a);
}
else{
st.push(std::stoi(t));
}
}
return st.top();
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) Time O(N) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.