↻one more pass.
Stack · Medium

Evaluate Reverse Polish Notation: the idea to remember.

Evaluate a valid postfix expression of integers and the four arithmetic operators.

Solve on LeetCode ↗

The core insight

Push operands. On an operator pop the right operand first, then the left.

Why it works

The stack holds values of completed subexpressions that have not yet been consumed.

The mistake to avoid

Order matters for subtraction and division; the first popped value is the right operand.

Time: O(n)Space: O(n)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int evalRPN(String[] tokens) {
    Deque<Integer> stack = new ArrayDeque<>();
    for (String token : tokens) {
        if (token.length() == 1 && "+-*/".contains(token)) {
            int right = stack.pop(), left = stack.pop();
            switch (token) {
                case "+": stack.push(left + right); break;
                case "-": stack.push(left - right); break;
                case "*": stack.push(left * right); break;
                case "/": stack.push(left / right); break;
            }
        } else stack.push(Integer.parseInt(token));
    }
    return stack.pop();
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.