Evaluate Reverse Polish Notation

MediumStack
Asked byGoogleLinkedInAmazonMicrosoftFacebookOracle

Problem

Evaluate an arithmetic expression given in Reverse Polish (postfix) Notation, where operands and operators are provided as tokens. Valid operators are +, -, *, and /, and division truncates toward zero.

Examples

Example 1
Input:tokens = ["2","1","+","3","*"]
Output:9
(2 + 1) * 3 = 9.
Example 2
Input:tokens = ["4","13","5","/","+"]
Output:6
4 + (13 / 5) = 6.

Constraints

  • 1 <= tokens.length <= 10^4

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Stack pattern

A stack is last-in-first-out — the most recently added item is the first one removed. It's the natural fit whenever "the most recent unmatched thing" matters, like nested brackets or undo history.

Look for this pattern when

  • You're validating nested or paired structures (parentheses, tags, nested expressions).
  • You need to track "the most recent X that hasn't been resolved yet."
  • You're looking for the next larger or smaller element relative to each position.

Read the full Stack guide →

Video walkthroughs

Original problem on LeetCode ↗

More Stack problems