Problem statement

https://binarysearch.com/problems/Postfix-Notation-Evaluation/

Solution

Equal to Leetcode 0150. Evaluate Reverse Polish Notation.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, tokens):
        stack = []
        def f(a, b, c):
            if c == "+": return a+b
            if c == "-": return b-a
            if c == "*": return a*b
            if c == "/": return int(b/a)
            
        for token in tokens:
            if token in "*/+-":
                stack.append(f(stack.pop(), stack.pop(), token))
            else:
                stack.append(int(token))
        return stack[-1]