◀ THE GRIND — STACK

Evaluate Reverse Polish Notation

MEDIUM✓ CHIP-TIMEDLC #150 — FULL STATEMENT ↗

The drill: Evaluate an expression written in postfix (Reverse Polish) form: an operator token acts on the two numbers immediately before it, and the whole array reduces to a single value.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

An array of string tokens arrives representing an arithmetic expression written in postfix — Reverse Polish — notation, where numbers appear before the operator that combines them.

A number token is a plain operand. An operator token — +, -, *, or / — always acts on the two operands that came immediately before it in the scan, replacing all three with a single resulting value.

Division truncates toward zero, and the tokens are always arranged so the whole array reduces to exactly one final value once every operator has been applied.

EX 01
tokens = ["6", "2", "/"]
3
PLAIN DIVISION
EX 02
tokens = ["10", "3", "-", "2", "*"]
14
SUBTRACTION FEEDS A MULTIPLICATION
EX 03
tokens = ["-5", "3", "+"]
-2
NEGATIVE OPERAND
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Every operator here needs exactly the two most recent numbers it hasn't consumed yet — the ones nearest to it in the scan, not the oldest ones.

HINT 2 THE STRUCTURE

A stack holds “numbers not yet used.” Push numbers as you read them; on an operator, pop the top two, combine them, and push the result back as a new “number.”

HINT 3 ONE STEP FROM THE ANSWER

Pop b then a, in that order — operand order matters for subtraction and division — compute a OP b, and push it back. After the last token, the stack holds exactly one value: the answer.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE OPERAND STACKPATTERN · OPERAND STACKtokens = ["10", "3", "-", "2", "*"]
10
3
-
2
*
OPERAND STACK
— empty —
STEP 1

Numbers push onto a stack; an operator pops the two most recent and pushes the result back.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/evaluate-reverse-polish-notation.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        ops = {"+", "-", "*", "/"}
        for t in tokens:
            if t in ops:
                b = stack.pop()
                a = stack.pop()
                if t == "+":
                    stack.append(a + b)
                elif t == "-":
                    stack.append(a - b)
                elif t == "*":
                    stack.append(a * b)
                else:
                    stack.append(int(a / b))  # truncate toward zero
            else:
                stack.append(int(t))
        return stack[0]
TIME O(N)SPACE O(N)PYTHON · RACE PACE · 19 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED