Browse curriculum

FAANGPrep Sprint

Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation (Postfix).

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.

  1. Initialize an empty stack.
  2. Iterate through each token.
  3. If token is a number, push it to the stack.
  4. If token is an operator:
    • pop the top two elements (say b is top, a is next).
    • Perform a <op> b.
    • push the result back.
  5. 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.