Evaluate Reverse Polish Notation — LeetCode 150 Python Solution

MediumStackArrayMath
Problem
#150
Pattern
Stack
Reading time
3 min

The problem

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression.

Example

Input
tokens = ["2","1","+","3","*"]
Output
9
Explanation
((2 + 1) * 3) = 9

Python solution

Python
import operator


class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        opt = {
            "+": operator.add,
            "-": operator.sub,
            "*": operator.mul,
            "/": operator.truediv,
        }
        s = []
        for token in tokens:
            if token in opt:
                s.append(int(opt[token](s.pop(-2), s.pop(-1))))
            else:
                s.append(int(token))
        return s[0]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 150. Evaluate Reverse Polish Notation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 150. Evaluate Reverse Polish Notation?
LeetCode 150. Evaluate Reverse Polish Notation is rated Medium on LeetCode.
What is the time complexity of LeetCode 150. Evaluate Reverse Polish Notation?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 150. Evaluate Reverse Polish Notation?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 150. Evaluate Reverse Polish Notation cover?
LeetCode 150. Evaluate Reverse Polish Notation is tagged Stack, Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview