Problem statement

https://binarysearch.com/problems/Word-Machine/

Solution

Just simulate process.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, ops):
        stack = []
        for op in ops:
            if op == "POP":
                if not stack: return -1
                stack.pop()
            elif op == "DUP":
                if not stack: return -1
                stack += [stack[-1]]
            elif op == "+":
                if len(stack) < 2: return -1
                stack += [stack.pop() + stack.pop()]
            elif op == "-":
                if len(stack) < 2: return -1
                stack += [stack.pop() - stack.pop()]
            else:
                stack += [int(op)]

        return stack[-1]