Evaluate Reverse Polish Notation Visualizer & Step-by-Step Algorithm Solution

Evaluate arithmetic expressions written in Reverse Polish Notation (postfix) using a LIFO operand stack.

Category: stack | Difficulty: Medium

Tags: Stack, Array, Math, Postfix Evaluation

Evaluate Reverse Polish Notation

RPN Tokens
2
0
1
1
+
2
3
3
*
4
Push / Pop (Top)
(Empty Stack)
Operand Stack (LIFO)
100%
state
stack[]
stackSize0
tokens[2, 1, +, 3, *]
length5
Initialization
1/29
Explanation

Start evalRPN with tokens = ["2", "1", "+", "3", "*"].

Source Code
1function evalRPN(tokens: string[]): number {
2 const stack: number[] = [];
3 for (let i = 0; i < tokens.length; i++) {
4 const token = tokens[i];
5 if (token !== '+' && token !== '-' && token !== '*' && token !== '/') {
6 stack.push(Number(token));
7 } else {
8 const a = stack.pop()!;
9 const b = stack.pop()!;
10 let res = 0;
11 if (token === '+') res = b + a;
12 else if (token === '-') res = b - a;
13 else if (token === '*') res = b * a;
14 else res = Math.trunc(b / a);
15 stack.push(res);
16 }
17 }
18 return stack.pop()!;
19}