InterviewHubPRO
Section Overview
Q31

Question 31 of 100

Part 4: Stacks, Queues & Monotonic Stacks (29 - 36)

31%
DSA Patterns (Multi-Lang)•Part 4: Stacks, Queues & Monotonic Stacks (29 - 36)

Evaluate Reverse Polish Notation.

In Simple Words: Operands are pushed onto a stack. When an operator is encountered, pop the top two operands, evaluate the expression (b op a), and push result back.

  • Time: $O(N)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
def evalRPN(tokens: list[str]) -> int:
    stack = []
    for t in tokens:
        if t == '+':
            stack.append(stack.pop() + stack.pop())
        elif t == '-':
            a, b = stack.pop(), stack.pop()
            stack.append(b - a)
        elif t == '*':
            stack.append(stack.pop() * stack.pop())
        elif t == '/':
            a, b = stack.pop(), stack.pop()
            stack.append(int(b / a))  # truncate towards zero
        else:
            stack.append(int(t))
    return stack[0]