Evaluate Reverse Polish Notation

Medium Subject: Stack
Time Complexity
O(N)
Space Complexity
O(N)

Problem Description

You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation. Evaluate the expression and return the resulting value.

Optimal Solution

Python
def evalRPN(tokens):
    stack = []
    ops = {"+", "-", "*", "/"}
    for token in tokens:
        if token in ops:
            b = stack.pop()
            a = stack.pop()
            if token == "+":
                stack.append(a + b)
            elif token == "-":
                stack.append(a - b)
            elif token == "*":
                stack.append(a * b)
            else:
                stack.append(int(a / b))
        else:
            stack.append(int(token))
    return stack[0]