Evaluate Reverse Polish Notation

Work out the value of an expression whose operators come after their numbers, using a stack.

Given an array of strings tokens that holds an arithmetic expression in Reverse Polish Notation, return the value of the expression as an integer. Each string, called a token, is either a number or an operator. In this notation an operator comes after the two numbers it works on, so "2 1 +" means 2 + 1.

The operators are +, -, * and /. Division keeps only the whole part of the result and drops the rest, so 7 / 2 is 3 and -7 / 2 is -3. The expression is always valid.

Example 1
Input: tokens = ["2", "1", "+", "3", "*"]
Output: 9
Explanation: (2 + 1) * 3.
Example 2
Input: tokens = ["4", "13", "5", "/", "+"]
Output: 6
Explanation: 4 + (13 / 5) = 4 + 2.
Example 3
Input: tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Solution

The Idea

On paper, adding 2 and 1 and then multiplying by 3 is written (2 + 1) * 3. The brackets matter: without them, 2 + 1 * 3 means 2 + 3, which is 5, because multiplication goes first. Reverse Polish Notation, also called postfix notation, needs neither brackets nor rules about which operator goes first. The numbers come first and the operator right after them, so (2 + 1) * 3 becomes 2 1 + 3 *, the tokens of Example 1.

How do you read it? Go from left to right, and each time an operator appears, apply it to the two values just before it. In Example 1, the + takes 2 and 1 and gives 3. Then the * takes that 3 and the next 3 and gives 9.

Example 2, 4 13 5 / +, shows that "the two values just before it" needs care. The / takes 13 and 5 and gives 2. Those two numbers are now used up, and the 2 takes their place, right after the 4. So the + adds 4 and 2, and the answer is 6.

So which two values does an operator take? Always the two newest values that are not used up yet, where a result counts as a new value. Keeping values so that the newest one comes back first is exactly what a stack does. A stack works like a pile of plates: push puts a value on top, and pop takes the top value off again.

Look at the picture below. It reads Example 2 one token at a time and shows the stack after each token, with the top of the stack as its highest box.

Evaluating 4 13 5 / + with a stack. The numbers 4, 13 and 5 are pushed. The / pops 5 and 13 and pushes 13 / 5 = 2, leaving 4 and 2. The + pops 2 and 4 and pushes 4 + 2 = 6, the answer.

The first three columns push 4, 13 and 5, so after "5" the stack holds all three, with 5 on top. In the "/" column, the operator pops 5, then 13, and pushes 13 / 5 = 2, the orange 2. Now 2 sits on top of 4, so in the last column the "+" pops 2 and 4 and pushes 4 + 2 = 6. That one value left on the stack is the answer.

Solution Approach

Turning that idea into code means settling four things: what to do with each token, which popped value goes on which side of the operator, how to tell a negative number from a minus sign, and how to divide. Handling each token on a stack is also faster than a simpler way that rewrites the list.

Handling each token

What should happen when a token arrives? A number is pushed onto the stack. An operator pops two values, applies itself to them, and pushes the result back, where a later operator can use it. When the tokens run out, a valid expression leaves exactly one value on the stack, and that value is the answer.

A simpler way works on the list itself: find the first operator, replace it and the two numbers before it with the result, and start again from the beginning. That gives the right answer, but every replacement means another walk over the list, so a list of n tokens can take about n² steps. The stack never looks back, and each token is handled once, as it is read.

Operand order

Which popped value goes on the left of the operator? The two values an operator works on are called its operands. The value pushed last comes off first, and it is the one written later in the expression, so the first pop gives the right operand. For 13 5 /, the pops give 5 and then 13, and the result is 13 / 5, not 5 / 13. For + and * the order makes no difference, but for - and / it does.

Negative numbers and the minus sign

How do we tell the operator "-" from a negative number such as "-11" in Example 3? Both start with a minus sign, so looking at the first character is not enough. Comparing the whole token is enough, because only the one-character string "-" is the operator. Every other token is a number, and Integer.parseInt reads "-11" as -11.

Division toward zero

Does Java divide the way the problem asks? Yes. Dividing one int by another keeps the whole part and drops the rest, which moves the result toward zero, so -7 / 2 gives -3. Rounding down would give -4, which is what Math.floorDiv(-7, 2) returns, so that method would be wrong here.

Java Solution

The method evalRPN works in these steps:

  1. First, create an empty stack, stack, as an ArrayDeque<Integer>. ArrayDeque is a Java class that keeps values in an array and can add or remove them at either end. Its push and pop both work on the front, which serves as the top of the stack.
  2. Read the tokens one by one with a loop over tokens. Inside it, a switch compares each whole token with "+", "-", "*" and "/".
  3. For an operator, pop the top value into b, the right operand, and the value under it into a, the left operand. A second switch computes a + b, a - b, a * b or a / b, and the result is pushed.
  4. Any other token is a number: Integer.parseInt turns it into an int, which is pushed.
  5. After the last token, pop the one value left on the stack and return it.

The main method runs the three examples, then 3 4 - to check the operand order, -7 2 / to check division of a negative number, and an expression that is just the number 5.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class ReversePolishNotation {

    public static int evalRPN(String[] tokens) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (String token : tokens) {
            switch (token) {
                case "+", "-", "*", "/" -> {
                    int b = stack.pop();          // the right operand is on top
                    int a = stack.pop();          // the left operand is under it
                    stack.push(switch (token) {
                        case "+" -> a + b;
                        case "-" -> a - b;
                        case "*" -> a * b;
                        default -> a / b;         // int division truncates toward zero
                    });
                }
                default -> stack.push(Integer.parseInt(token));   // a number, maybe "-11"
            }
        }
        return stack.pop();
    }

    public static void main(String[] args) {
        System.out.println(evalRPN(new String[] {"2", "1", "+", "3", "*"}));
        System.out.println(evalRPN(new String[] {"4", "13", "5", "/", "+"}));
        System.out.println(evalRPN(new String[] {"10", "6", "9", "3", "+", "-11", "*", "/", "*",
                "17", "+", "5", "+"}));
        System.out.println(evalRPN(new String[] {"3", "4", "-"}));
        System.out.println(evalRPN(new String[] {"-7", "2", "/"}));
        System.out.println(evalRPN(new String[] {"5"}));
    }
}

Running it prints:

Output
9
6
22
-1
-3
5

Look at the 6 on the second line, from Example 2: 13 / 5 gave 2, and 4 + 2 gave 6. If the two pops were swapped, so that the first value popped became a, the / would compute 5 / 13 = 0, and that version prints 4 for Example 2. The 22 on the third line is Example 3, where "-11" was read as a number and not as a minus.

The -1 on the fourth line comes from 3 4 -, so the code computed 3 - 4; the swapped version prints 1 there. The -3 on the fifth line is -7 / 2 with the rest dropped toward zero. On the last line, a lone number is already a valid expression: it is pushed, nothing pops it until the end, and the method returns 5.

The original implementation, ReversePolishNotation.java, is on GitHub.

Complexity

Each token is handled once, with at most two pops and one push.

  • Time: O(n) for n tokens, because a number costs one short parse and one push, and an operator costs two pops and one push, each a fixed amount of work on an ArrayDeque.
  • Space: O(n), because the stack holds the numbers that no operator has used yet. When all the numbers come first, as in 1 2 3 + +, about half of the tokens sit on the stack at the same time, here three of the five.

A stack of values also keeps the score in Baseball Game.