Evaluate Reverse Polish Notation

MediumStackLeetCode 150 ↗World 2-19
0:00 / 0:00

Work out an expression written with operators after their numbers. Push each number on a stack; each operator pops two and pushes the result.

▼

The problem

LeetCode 150 (Medium). Given an array of string tokens in Reverse Polish (postfix) Notation, with the operators +, -, * and /, return the value of the expression. Division between two integers truncates toward zero; the input is always valid and never divides by zero.

Examples (LeetCode's): ["2","1","+","3","*"] → 9 ((2 + 1) × 3), ["4","13","5","/","+"] → 6 (4 + 13 / 5) and ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] → 22.

TRY IT ON LEETCODE ▶

The solution

def evalRPN(tokens):
    stack = []
    for tok in tokens:
        if tok in "+-*/":
            b = stack.pop()
            a = stack.pop()
            if tok == "+": stack.append(a + b)
            elif tok == "-": stack.append(a - b)
            elif tok == "*": stack.append(a * b)
            else: stack.append(int(a / b))
        else:
            stack.append(int(tok))
    return stack[0]

Transcript

Evaluate Reverse Polish Notation. Every operator comes after its two numbers, so two, one, plus means two plus one. Given the tokens, return the value. Division truncates toward zero: seven over two is three, and minus seven over two is minus three.

Take two, one, plus, three, times. Two plus one is three, times three is nine. Or four, thirteen, five, divide, plus. Thirteen over five is two, plus four is six.

The slow way: find two numbers followed by an operator, collapse them into one, and scan again from the start. That's about n over two passes of up to n tokens: order n squared.

The trick is one stack. Picture a pancake griddle. Every number is a pancake flipped onto the plate. Every operator is the chef: he lifts the top two, b first, since it was on top, then a, and presses them into one: a operator b. Order matters: ten, six, minus is four, not minus four.

Now the big one. Ten, six, nine and three land. Plus: nine plus three is twelve. Minus eleven lands. Times: twelve times minus eleven is minus one hundred thirty-two. Divide: six over minus one hundred thirty-two is zero, truncated toward zero. Floor division would give minus one. Times: ten times zero is zero. Seventeen, plus: seventeen. Five, plus: twenty-two.

In code: for each token, if it's an operator, pop b, then a, and push a operator b, dividing with int of a over b. Otherwise, push the number. Return the one value left.

Each token is pushed once and each operator pops two: order n time. At worst, all the numbers come first, and the plate holds about half the tokens: order n space.

Push the numbers, pop two, combine. That's Evaluate Reverse Polish Notation.