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
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
Output: 9
Explanation: (2 + 1) * 3.
Example 2
Output: 6
Explanation: 4 + (13 / 5) = 4 + 2.
Example 3
Output: 22
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: pushpop
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.
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
Division toward zero
Does Java divide the way the problem asks? Yes. Dividing one intMath.floorDiv(-7, 2)
Java Solution
The method evalRPN
- First, create an empty stack,
, as anstack .ArrayDeque<Integer> is a Java class that keeps values in an array and can add or remove them at either end. ItsArrayDeque andpush both work on the front, which serves as the top of the stack.pop - Read the tokens one by one with a loop over
. Inside it, atokens compares each wholeswitch withtoken ,"+" ,"-" and"*" ."/" - For an operator, pop the top value into
, the right operand, and the value under it intob , the left operand. A seconda computesswitch ,a + b ,a - b ora * b , and the result is pushed.a / b - Any other token is a number:
turns it into anInteger.parseInt , which is pushed.int - After the last token, pop the one value left on the stack and return it.
The main
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:
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 -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,
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