FAANGPrep Sprint
Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation (Postfix).
MediumSolve on LeetCode
Problem Understanding
The array tokens holds an arithmetic expression written in Reverse Polish Notation, where each operator comes after its two operands. Compute its value and return it as an integer.
Valid Operators: +, -, *, /. Integer division truncates toward zero.
Example:
- Input:
["2","1","+","3","*"] - Logic:
((2 + 1) * 3) = 9 - Output:
9 - Input:
["4","13","5","/","+"] - Logic:
(4 + (13 / 5)) = 6
Algorithm Strategy
RPN is perfectly suited for a Stack.
- Initialize an empty stack.
- Iterate through each token.
- If token is a number,
pushit to the stack. - If token is an operator:
popthe top two elements (saybis top,ais next).- Perform
a <op> b. pushthe result back.
- Final result is the only element left in the stack.
Interactive Visualization
5 TOKENS
READ TOKEN
tokens
i
2
1
+
3
*
stack
empty
a
—
b
—
Result
—
Read “2”
Next
A number: push 2
Tokens
Visualize how operands wait on the stack until an operator consumes them.
