TRT
Sign in
mediumFoundationsLeetCode#operand stack

Evaluate reverse Polish notation

Evaluate an arithmetic expression written in postfix order with a single stack of operands.

The Runtime Theory Team1 min read
Taught inStacks and the LIFO ruleA stack only lets you touch its most recent item. That restriction makes it cheap to build on an array, and it is exactly what nested structure, undo and matching brackets need.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

intokens = ["2", "1", "+", "3", "*"]

out9

intokens = ["4", "13", "5", "/", "+"]

out6

intokens = ["-7", "2", "/"]

out-3

Given an expression in reverse Polish notation as a list of tokens, with the operators +, -, * and /, return its value. Division truncates toward zero.

Before you code

In postfix notation, every operator applies to the two most recent values. That is a stack: push numbers, and let each operator pop its operands and push its result.

Hints

  1. Pop the right operand first, then the left: for a b -, the result is a − b, not b − a.
  2. Truncate toward zero: in Python, int(a / b), not a // b, which rounds toward negative infinity (-7 // 2 is -4, but the answer is -3).
  3. At the end, the stack holds exactly one value: the answer.

Production & complexity notes

When solving Evaluate reverse Polish notation on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Stacks and the LIFO rule to reinforce the underlying pattern.

What it practices

The operand stack that calculators and virtual machines use, from Stacks and the LIFO rule.

Not started

Sign in to save your learning progress.

Sign in to save