# [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) ###### tags: `Leetcode`, `Medium`, `Stack` ## Approach * We keep adding numbers from our input list onto the stack * When we encounter a symbol then we pop the last two numbers from the stack * Then we perform the operation corresponding to the symbol on the two popped elements * The result is added back to the stack and the process is repeated until the input list is exhausted and only one element is left behind in the stack * Return the only element in the stack ## Asymptotic Analysis ### Time Complexity: **O(N)** ### Space Complexity: **O(N)** ## Code ``` python import math from typing import List class ReversePolishNotation: def _is_integer(self, num: str): return num.isdigit() or (num.startswith('-') and num[1:].isdigit()) def _operate(self, num1: int, num2: int, operation: str) -> int: if operation == '+': return num1 + num2 elif operation == '-': return num1 - num2 elif operation == '*': return num1 * num2 elif operation == '/': return int(num1 / num2) else: return -1 def eval_rpn(self, tokens: List[str]) -> int: stack = [] for token in tokens: if self._is_integer(token): stack.append(int(token)) else: operator = token num2, num1 = int(stack.pop()), int(stack.pop()) result = self._operate(num1, num2, operator) stack.append(result) return stack[-1] nums_list = ["4", "13", "5", "/", "+"] print(ReversePolishNotation().eval_rpn(nums_list)) ```