Evaluate postfix (RPN)

Evaluate an expression written with the operator after its operands, such as "3 4 +". No brackets or precedence rules needed.

Time O(n)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Numbers wait on the stack. An operator takes the top two numbers, applies itself, and pushes the result back for a later operator to use.

Code

public static int EvalRpn(string[] tokens) {
    var stack = new Stack<int>();
    foreach (string t in tokens) {
        if (int.TryParse(t, out int n)) { stack.Push(n); continue; }
        int b = stack.Pop(), a = stack.Pop();
        stack.Push(t switch {
            "+" => a + b, "-" => a - b,
            "*" => a * b, _ => a / b });
    }
    return stack.Pop();
}
static int evalRpn(String[] tokens) {
    Deque<Integer> stack = new ArrayDeque<>();
    for (String t : tokens) {
        if (t.matches("-?\\d+")) { stack.push(Integer.parseInt(t)); continue; }
        int b = stack.pop(), a = stack.pop();
        switch (t) {
            case "+": stack.push(a + b); break;
            case "-": stack.push(a - b); break;
            case "*": stack.push(a * b); break;
            default: stack.push(a / b);
        }
    }
    return stack.pop();
}
int evalRpn(const vector<string>& tokens) {
    stack<int> st;
    for (const string& t : tokens) {
        if (isdigit(t.back())) { st.push(stoi(t)); continue; }
        int b = st.top(); st.pop(); int a = st.top(); st.pop();
        st.push(t == "+" ? a + b : t == "-" ? a - b
              : t == "*" ? a * b : a / b);
    }
    return st.top();
}
def eval_rpn(tokens: list[str]) -> int:
    stack = []
    for t in tokens:
        if t.lstrip('-').isdigit(): stack.append(int(t)); continue
        b, a = stack.pop(), stack.pop()
        stack.append(a + b if t == '+' else a - b if t == '-' else a * b if t == '*' else int(a / b))
    return stack.pop()

Tips

In the .NET library

int.TryParse separates numbers from operators without exceptions. The switch expression is a compact way to map an operator to its result. C# integer division truncates towards zero.