MediumNo. 0150

Evaluate Reverse Polish Notation — LeetCode 150 Python Solution

Pattern
Stack
Topics
Stack, Array, Math
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
2197Replace Non-Coprime Numbers in ArrayHard
0042Trapping Rain WaterHard
0224Basic CalculatorHard
0227Basic Calculator IIMedium
0321Create Maximum NumberHard
0445Add Two Numbers IIMedium

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.

Free to download. Check it runs on your machine, then pick a plan.