CodeArchon

mediumStackAmazonLinkedIn

Postfix Expression Evaluator

A calculator receives tokens in reverse-Polish order (operator after its operands). Compute the final integer.

Given a token array mixing integers and `+ - * /`, evaluate the postfix expression. Division truncates toward zero.

Choose approach

Input
2
1
+
3
*
top
1/7
Narrationstep 1 of 7

Scan tokens left to right. Numbers push; operators pop two, apply, push result.

1def postfix_eval(tokens: list[str]) -> int:
2 st: list[int] = []
3 for t in tokens:
4 if t in {'+', '-', '*', '/'}:
5 b = st.pop(); a = st.pop()
6 if t == '+': st.append(a + b)
7 elif t == '-': st.append(a - b)
8 elif t == '*': st.append(a * b)
9 else: st.append(int(a / b)) # truncate toward 0
10 else:
11 st.append(int(t))
12 return st[0]
Variables
i=0

How to think about it

  1. Postfix is pre-parenthesized by position — no operator precedence needed.
  2. Stack holds pending operands.
  3. Operator consumes top two in reverse of their push order.
  4. Final stack length is 1 for any well-formed expression.

Edge cases to catch in interview

  • Division truncates toward 0 (not toward −∞).
  • Negative operands — parse as integers.
  • Deep expressions grow the stack to O(n/2).

Examples

Example 19
{"tokens":["2","1","+","3","*"]}

(2 + 1) * 3.

Example 26
{"tokens":["4","13","5","/","+"]}

4 + (13 / 5).

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed