Skip to content

150. Evaluate Reverse Polish Notation

Edited by Charles

Medium · Python · Stack

Problem

Read the original problem on LeetCode.

The official page contains the problem statement, examples, and constraints.

Explanation, examples & other approaches

Core idea

The operator always comes when the stack has enough numbers to calculate. Iterate the whole list, append the element to the stack if it is a digit character; else, pop two elements out and complete the calculation.

Original study notes follow, including intermediate snippets and earlier attempts.

Note:

  1. The operator always comes when the stack has enough numbers to calculate.
  2. Iterate the whole list, append the element to the stack if it is a digit character; else, pop two elements out and complete the calculation.
  3. For the division, use int(a / b) to make sure the result is the integer part.
Study record
Field Value
Attempts 1
Mastery ❚
The Latest Attempt January 9, 2026

Python solution

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        n = len(tokens)
        stack = []
        operators = ['+', '-', '*', '/']

        for i in range(n):

            if tokens[i] not in operators:
                stack.append(int(tokens[i]))

            else:
                b = stack.pop()
                a = stack.pop()

                if tokens[i] == operators[0]:
                    stack.append(a + b)
                if tokens[i] == operators[1]:
                    stack.append(a - b)
                if tokens[i] == operators[2]:
                    stack.append(a * b)
                if tokens[i] == operators[3]:
                    stack.append(int(a / b))

        return stack.pop()

Back to Day 10 Stack & Queue II · All Algorithm notes