Algo-Sim › Stacks & Monotonic Stack

Evaluate Reverse Polish Notation

Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

Evaluate a postfix expression: push numbers, and let each operator combine the top two.

Problem

You are given tokens, an arithmetic expression in Reverse Polish Notation: each operator follows its two operands. Evaluate it and return the integer result. The operators are +, -, * and /, and division truncates toward zero.

Constraints

Edge cases to test

Follow-up questions

Why does Python need int(a / b)?
// floors toward −∞, while the task truncates toward 0; int(a / b) (or math.trunc) matches Java and C++.
How would you turn infix into RPN?
Shunting-yard: an operator stack ordered by precedence, flushed by lower-precedence operators and closing parentheses. O(n).

Solution

Java

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(), a = stack.pop();
            stack.push(switch (t) {
                case "+" -> a + b;
                case "-" -> a - b;
                case "*" -> a * b;
                default -> a / b;
            });
        } else {
            stack.push(Integer.parseInt(t));
        }
    }
    return stack.pop();
}

Python

def eval_rpn(tokens):
    stack = []
    for t in tokens:
        if t in ('+', '-', '*', '/'):
            b, a = stack.pop(), 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.pop()

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int evalRPN(vector<string> &tokens) {
        deque<int> stack = {};
        for (string t : tokens) {
            if ((t == "+") || (t == "-") || (t == "*") || (t == "/")) {
                int b = stack.back();
                stack.pop_back();
                int a = stack.back();
                stack.pop_back();
                int result = t == "+" ? a + b : t == "-" ? a - b
                                            : t == "*"   ? a * b
                                                         : a / b;
                stack.push_back(result);
            } else {
                stack.push_back(stoi(t));
            }
        }
        return stack.back();
    }
};

More Stacks & Monotonic Stack problems