AlgoMaster Logo

Evaluate Reverse Polish Notation

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Stack-based Evaluation

Intuition:

The Reverse Polish Notation (RPN) is a mathematical notation in which every operator follows all of its operands. This makes it very straightforward to evaluate using a stack, as stacks naturally follow the Last-In-First-Out (LIFO) principle.

Traverse the tokens:

  • If the token is a number, push it onto the stack.
  • If the token is an operator, pop the necessary operands from the stack, perform the operation, and push the result back onto the stack.

By the end of the process, the stack should contain just one element - the result of the expression.

Steps:

  1. Initialize an empty stack to hold integers.
  2. Iterate over each token:
    • If it's a number, convert it to an integer and push onto the stack.
    • If it's an operator (+-*/), pop the top two operands from the stack, apply the operator, and push the result back onto the stack.
  3. At the end of iteration, the stack will contain one element which is the result.

Code: