DSA Tracker

Visualize

Evaluate Reverse Polish Notation

The key insight: RPN encodes evaluation order without needing parentheses or precedence rules — every operator appears immediately after the two operands it applies to. A stack captures exactly that for free: push operands as you see them, and the moment you hit an operator, the two values it needs are automatically the last two things pushed. Pop the two most recent operands, apply the operator, and push the result back so it's ready for whatever operator comes next.

Details

Animated on: Evaluate the expression tokens = ["2","1","+","3","*"] = (2+1)*3 = 9.

Problem:Evaluate Reverse Polish NotationMedium

Stack

step 1 / 6

2
[0]

Token "2" is a number. Push 2 onto the stack. Stack: [2]

  • operand=0· arr[0] = 2
Pseudocode
1FUNCTION evalRpn(tokens):
2 make an empty stack
3 FOR each token tok in tokens:
4 IF tok is a number: push tok onto the stack
5 ELSE:
6 pop the top of the stack into b
7 pop the next top into a
8 CHECK the operator tok:
9 if '+': push a + b
10 if '-': push a - b
11 if '*': push a * b
12 if '/': push a / b truncated toward zero
13 END CHECK
14 END IF
15 END FOR
16 RETURN the only value left on the stack

← / → step · space play · Home restart

Every step in words

Show all 6 steps
  1. Token "2" is a number. Push 2 onto the stack. Stack: [2]
  2. Token "1" is a number. Push 1. Stack: [2, 1]
  3. Token "+" is an operator. Pop b=1, pop a=2, compute 2+1=3, push result. Stack: [3]
  4. Token "3" is a number. Push 3. Stack: [3, 3]
  5. Token "*" is an operator. Pop b=3, pop a=3, compute 3*3=9, push result. Stack: [9]. Final answer: 9.
  6. All 5 tokens processed, exactly one value remains on the stack — that's the answer: 9.

Now solve it yourself

Watching is the first half. The second is writing it without the animation.