Browse curriculum

Evaluate Reverse Polish Notation (LeetCode 150)

Evaluate Reverse Polish Notation (LeetCode 150): evaluate the value of an arithmetic expression in Reverse Polish Notation (Postfix).

Problem Understanding

The array tokens holds an arithmetic expression written in Reverse Polish Notation, where each operator comes after its two operands. Compute its value and return it as an integer.

Valid Operators: +, -, *, /. Integer division truncates toward zero.

Example:

  • Input: ["2","1","+","3","*"]
  • Logic: ((2 + 1) * 3) = 9
  • Output: 9
  • Input: ["4","13","5","/","+"]
  • Logic: (4 + (13 / 5)) = 6

Algorithm Strategy

RPN is perfectly suited for a Stack.

  1. Initialize an empty stack.
  2. Iterate through each token.
  3. If token is a number, push it to the stack.
  4. If token is an operator:
    • pop the top two elements (say b is top, a is next).
    • Perform a <op> b.
    • push the result back.
  5. Final result is the only element left in the stack.

Interactive Visualization

5 TOKENS

READ TOKEN

tokens

i

2
1
+
3
*

stack

empty

a

:

b

:

Result

:

 

Read “2”

Next

A number: push 2

Free preview: the first 4 of 13 steps

Tokens

Visualize how operands wait on the stack until an operator consumes them.

Dry Run

Input: ["4", "13", "5", "/", "+"]

Token Action Stack
4 Push 4 [4]
13 Push 13 [4, 13]
5 Push 5 [4, 13, 5]
/ Pop 5, 13. 13 / 5 = 2. Push 2. [4, 2]
+ Pop 2, 4. 4 + 2 = 6. Push 6. [6]
End Result 6

Edge Cases & Common Mistakes

  • Division Order: a / b vs b / a. Remember: first popped is b (right operand).
  • Truncation: Integer division in Python behaves differently for negatives (-1 // 2 = -1 vs C++ 0). Use int(a / b) to truncate towards zero.

Solution

Stack Logic.

Evaluate Reverse Polish Notation Code
1var evalRPN = function(tokens) {
2 const stack = [];
3 for (const t of tokens) {
4 if (t === '+' || t === '-' || t === '*' || t === '/') {
5 const b = stack.pop();
6 const a = stack.pop();
7 if (t === '+') stack.push(a + b);
8 else if (t === '-') stack.push(a - b);
9 else if (t === '*') stack.push(a * b);
10 else stack.push(Math.trunc(a / b));
11 } else {
12 stack.push(Number(t));
13 }
14 }
15 return stack[0];
16};

Evaluate Reverse Polish Notation in Python, Java, C++, TypeScript and C

Evaluate Reverse Polish Notation in Python
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for t in tokens:
            if t in ("+", "-", "*", "/"):
                b = stack.pop()
                a = stack.pop()
                if t == "+": stack.append(a + b)
                elif t == "-": stack.append(a - b)
                elif t == "*": stack.append(a * b)
                else: stack.append(int(a / b))
            else:
                stack.append(int(t))
        return stack[0]
Evaluate Reverse Polish Notation in Java
class Solution {
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (String t : tokens) {
            if (t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")) {
                int b = stack.pop();
                int a = stack.pop();
                if (t.equals("+")) stack.push(a + b);
                else if (t.equals("-")) stack.push(a - b);
                else if (t.equals("*")) stack.push(a * b);
                else stack.push(a / b);
            } else {
                stack.push(Integer.parseInt(t));
            }
        }
        return stack.pop();
    }
}
Evaluate Reverse Polish Notation in C++
class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> st;
        for (const string& t : tokens) {
            if (t == "+" || t == "-" || t == "*" || t == "/") {
                int b = st.top(); st.pop();
                int a = st.top(); st.pop();
                if (t == "+") st.push(a + b);
                else if (t == "-") st.push(a - b);
                else if (t == "*") st.push(a * b);
                else st.push(a / b);
            } else {
                st.push(stoi(t));
            }
        }
        return st.top();
    }
};
Evaluate Reverse Polish Notation in TypeScript
function evalRPN(tokens: string[]): number {
    const stack: number[] = [];
    for (const t of tokens) {
         if (t === '+' || t === '-' || t === '*' || t === '/') {
             const b = stack.pop()!;
             const a = stack.pop()!;
             if (t === '+') stack.push(a + b);
             else if (t === '-') stack.push(a - b);
             else if (t === '*') stack.push(a * b);
             else stack.push(Math.trunc(a / b));
         } else {
             stack.push(Number(t));
         }
    }
    return stack[0];
};
Evaluate Reverse Polish Notation in C
int evalRPN(char ** tokens, int tokensSize){
    int* stack = (int*)malloc(tokensSize * sizeof(int));
    int top = -1;
    
    for (int i = 0; i < tokensSize; i++) {
        char* t = tokens[i];
        if (strlen(t) == 1 && (t[0] < '0' || t[0] > '9')) { // Operator
             int b = stack[top--];
             int a = stack[top--];
             if (t[0] == '+') stack[++top] = a + b;
             else if (t[0] == '-') stack[++top] = a - b;
             else if (t[0] == '*') stack[++top] = a * b;
             else stack[++top] = a / b;
        } else {
            stack[++top] = atoi(t);
        }
    }
    int res = stack[top];
    free(stack);
    return res;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Push numbers

    Push every number token onto the stack.

  2. Apply operators

    For an operator, pop b then a, and push a op b.

  3. Return the result

    After the last token, the single value on the stack is the result.

Frequently asked questions

How do you evaluate Reverse Polish Notation?

Read tokens left to right. Push each number; for an operator, pop the right operand b, then the left operand a, and push a op b. The one value left is the answer.


Why does the operand order matter?

The first value popped is the right-hand operand. For subtraction and division, a − b and a / b differ from b − a and b / a.


How should division be handled?

LeetCode 150 truncates toward zero, so 7 / -3 is -2. Python needs int(a / b) because // floors toward negative infinity.

New to the technique behind this problem? Watch it run step by step:

Stack Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description