Evaluate Reverse Polish Notation

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

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

Contents

Solution 1 - Using stack

First, let's understand this Reverse Polish Notation (RPN), in this notation we will have a list of operands and operators, when an operator is occurred, we ned to apply that operator on two left most operands. For example, consider this notation "4","13","5","/","+", here when first operator occurred '/' , we will apply this on two left side operands 13 and 5, so the result for this operation will be 13/5 = 2 (for this example, we are rounding down), now the notation becomes "4", "2", "+", we can now apply '+' operator on 4 and 2, so the result becomes 4+2 = 6.

In this approach, we are going to add elements into a Stack and when an operator symbol is occurred, we will remove top two elements from stack, and apply the operation and put back the result into stack.

Java
import java.util.Stack;

public class ReversePolishNotation {

    static int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(String token: tokens) {
            if("+".equals(token)) {
                int x1 = stack.pop();
                int x2 = stack.pop();
                stack.push(x2+x1);
            } else if("-".equals(token)) {
                int x1 = stack.pop();
                int x2 = stack.pop();
                stack.push(x2-x1);
            } else if("*".equals(token)) {
                int x1 = stack.pop();
                int x2 = stack.pop();
                stack.push(x2*x1);
            } else if("/".equals(token)) {
                int x1 = stack.pop();
                int x2 = stack.pop();
                stack.push(x2/x1);
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        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","+"}));
    }
}
Complexity Analysis:

Time complexity: Above code runs in O(n) time.
Space complexity: O(n).

Above implementations source code can be found at GitHub link for Java code