StackMedium

Evaluate RPN Visualizer

What is Evaluate RPN

Reverse Polish notation writes the operator after its two numbers. 2 1 + 3 * means (2 + 1) * 3.

Approach

The stack holds values that are still waiting for an operator. After the last token, one value remains.

Visualization & algorithm

Tokens, and the value stack
for each token:
if it is a number: push it
else:
right = pop
left = pop
push left operator right
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each token is handled once.
SpaceO(n)A run of numbers fills the stack.

Implementation

def solve(self, tokens):
    st = []
    for t in tokens:
        if t in '+-*/':
            b = st.pop(); a = st.pop()
            if t == '+': st.append(a + b)
            elif t == '-': st.append(a - b)
            elif t == '*': st.append(a * b)
            else: st.append(int(a / b))
        else:
            st.append(int(t))
    return st[-1]