Evaluate Reverse Polish Notation
Medium
Topics
Evaluate an arithmetic expression in Reverse Polish Notation given as a list of tokens. Valid operators are + - * /; division truncates toward zero.
Example 1
operator
In postfix the operator comes after its two operands, so no brackets and no precedence rules are needed. Push each number; on an operator pop two, apply, push the result. The last value left is the answer, 9. Order matters for
- and /: the first popped value is the right operand.Each chip is one token, left to right.
Input: tokens = ["2","1","+","3","*"] Output: 9
Example 2
operator
Input: tokens = ["4","13","5","/","+"] Output: 6
Constraints
- 1 <= tokens.length <= 10^4
- Tokens are integers or one of + - * /.
Editorial — intuition, approach, complexity and pitfalls
Intuition
In postfix notation an operator applies to the two most recent results — exactly stack behaviour. Push numbers; on an operator, pop two and push the result.
Approach
- Scan tokens with a stack.
- On a number, push it.
- On an operator, pop the top two (order matters for - and /), compute, and push back.
Dry Run
tokens 4 13 5 / +
4 push stack [4]
13 push stack [4, 13]
5 push stack [4, 13, 5]
/ pop 5, then pop 13 the SECOND pop is the left operand
13 / 5 = 2 stack [4, 2]
+ pop 2, then pop 4
4 + 2 = 6 stack [6]
answer 6
Pop order is the thing to get right. The stack hands back the most recent value
first, so the first pop is the RIGHT operand -- which matters not at all for + and
*, and entirely for - and /. Reversing them turns 13 / 5 into 5 / 13.
Division truncates toward zero, which is not what Python's `//` does on negatives.
`int(a / b)` gives -3 for -7 / 2 where `//` gives -4; on this input both happen to
agree at 6, so the bug hides until a negative appears.
No parentheses and no precedence rules exist in RPN -- the order is already
encoded in the token sequence, which is why a single stack and one pass suffice
with no parser.Complexity
- Time — O(n): one pass over the tokens.
- Space — O(n): the operand stack.
Common Pitfalls
- Division truncates toward zero (use int(a/b) in Python, not floor division for negatives).
Full Solution — all languages
class Solution:
def evalRPN(self, words):
stack=[]
for tok in words:
if tok in ('+','-','*','/'):
b=stack.pop(); a=stack.pop()
if tok=='+': stack.append(a+b)
elif tok=='-': stack.append(a-b)
elif tok=='*': stack.append(a*b)
else: stack.append(int(a/b))
else: stack.append(int(tok))
return stack[0]import java.util.*;
class Solution {
public int evalRPN(String[] words) {
Deque<Integer> stack=new ArrayDeque<>();
for(String tok:words) {
if(tok.equals("+")||tok.equals("-")||tok.equals("*")||tok.equals("/")) {
int b=stack.pop(),a=stack.pop();
if(tok.equals("+"))stack.push(a+b);
else if(tok.equals("-"))stack.push(a-b);
else if(tok.equals("*"))stack.push(a*b);
else stack.push(a/b);
} else stack.push(Integer.parseInt(tok));
}
return stack.pop();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int evalRPN(vector<string>& words) {
vector<long long> stack;
for(auto& tok:words) {
if(tok=="+"||tok=="-"||tok=="*"||tok=="/") {
long long b=stack.back();
stack.pop_back();
long long a=stack.back();
stack.pop_back();
if(tok=="+")stack.push_back(a+b);
else if(tok=="-")stack.push_back(a-b);
else if(tok=="*")stack.push_back(a*b);
else stack.push_back(a/b);
} else stack.push_back(stoll(tok));
}
return (int)stack[0];
}
};/**
* @param {string[]} words
* @return {number}
*/ var evalRPN = function(words) {
const stack=[];
for(const tok of words) {
if(tok==='+'||tok==='-'||tok==='*'||tok==='/') {
const b=stack.pop(),a=stack.pop();
if(tok==='+')stack.push(a+b);
else if(tok==='-')stack.push(a-b);
else if(tok==='*')stack.push(a*b);
else stack.push(Math.trunc(a/b));
} else stack.push(parseInt(tok,10));
}
return stack[0];
};