Browse Curriculum
FAANGPrep Sprint
Medium

Evaluate Reverse Polish Notation

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

Problem Understanding

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression and return 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

Step 1 / 1
Empty Stack
Top Index: -1

Initializing...

1x

Visualize how operands wait on the stack until an operator consumes them.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.