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.
Variables
i=0
How to think about it
- Postfix is pre-parenthesized by position — no operator precedence needed.
- Stack holds pending operands.
- Operator consumes top two in reverse of their push order.
- 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 1
9{"tokens":["2","1","+","3","*"]}
(2 + 1) * 3.
Example 2
6{"tokens":["4","13","5","/","+"]}
4 + (13 / 5).
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed