L2 · Working engineerStacks & queues~8 min · 6 tests#47

Evaluate a Postfix (RPN) Expression

Evaluate a space-separated postfix (Reverse Polish) expression with a stack in O(n), handling + - * / and operand order. Run tests in Python.

The problem

expression is a space-separated postfix expression of integers and the operators + - * /. Return its integer value.

  • Operands come before their operator: "2 3 + 4 *" means (2 + 3) * 4 = 20.
  • / truncates toward zero (so -7 / 2 is -3).

Examples

  1. Example 1

    Input

    eval_postfix('2 3 + 4 *')

    Expected output

    20
  2. Example 2

    Input

    eval_postfix('5 1 2 + 4 * + 3 -')

    Expected output

    14

+ 4 hidden tests on Submit — operand order, truncate toward zero.

Edge cases to ask about

  • Single number
  • Subtraction order
  • Negative division

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · eval_postfix
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Stack of operandsO(n)O(n)Operators pop two operands — the SECOND pop is the left operand.
    Walkthrough of the optimal approach (try it yourself first)

    Push numbers. On an operator, pop b first, then a, and push a op b — getting this order wrong breaks - and /. The final value is the only item left on the stack.

    Python's // floors (-7 // 2 == -4), so use int(a / b) when truncation is required.

    Complexity: O(n) time, O(n) space. Each token is processed once with O(1) stack work; the stack can hold up to n/2 operands.

    Reveal the reference solution
    def eval_postfix(expression):
        stack = []
        for token in expression.split():
            if token in ("+", "-", "*", "/"):
                b = stack.pop()
                a = stack.pop()
                if token == "+":
                    stack.append(a + b)
                elif token == "-":
                    stack.append(a - b)
                elif token == "*":
                    stack.append(a * b)
                else:
                    stack.append(int(a / b))
            else:
                stack.append(int(token))
        return stack[-1]

    Follow-ups interviewers ask

    • Convert infix to postfix (shunting-yard).
    • Validate malformed input.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Evaluate a Postfix (RPN) Expression in Python?

    The optimal solution runs in O(n) time and O(n) auxiliary space. Each token is processed once with O(1) stack work; the stack can hold up to n/2 operands.

    What follow-up questions do interviewers ask about Evaluate a Postfix (RPN) Expression?

    Convert infix to postfix (shunting-yard). Validate malformed input.