Evaluate Reverse Polish Notation

Stack

Problem

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Note:

  • Division between two integers should truncate toward zero.

  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

For example:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Input: ["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

Thought Process

  • Utilizing a stack is the best approach since we want the last items that we put in.

  • We only append numbers to the stack. We're popping the last two elements from the stack and doing the respective operations and adding this result back to the stack.

Solution

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        symbols = "+-*/"
        
        for i in tokens:
            if i in symbols:
                y = stack.pop()
                x = stack.pop()
                if i == "+":
                    stack.append(x+y)
                elif i == "-":
                    stack.append(x-y)
                elif i == "*":
                    stack.append(x*y)
                elif i == "/":
                    stack.append(int(x/y)) #Have to do int for some reason.Can't do '//'
            else:
                n = int(i)
                stack.append(n)
        return stack.pop()

Time Complexity

  • Time: O(n)

  • Space: O(n)

Last updated

Was this helpful?