Evaluate Reverse Polish Notation, explained

To evaluate Reverse Polish Notation, read the tokens left to right with a stack: push each number, and for each operator pop the right operand, then the left, apply the operator and push the result. The single value left at the end is the answer. It is one pass, O(n) time, and the only real trap is that division must round toward zero.

By Published 7 min read

What the problem gives you

You receive a list of string tokens. Each token is either a whole number, possibly negative, or one of the four operators +, -, * and /. The list is a valid postfix expression: every operator applies to the two values produced just before it. Return the integer result. Division between integers keeps only the whole part, dropping any fraction toward zero, so 7 divided by -3 is -2, not -3.

Expressions written for this page, evaluated by the code below
TokensSame thing in ordinary notationResult
8 5 - 4 *(8 − 5) × 412
7 2 5 - /7 ÷ (2 − 5)-2
9 4 - 2 8 * +(9 − 4) + (2 × 8)21
-7 2 /−7 ÷ 2-3
555
Expressions written for this page, evaluated by the code below. Scroll sideways on a small screen.

Before coding, confirm that the input is always valid, that there is no division by zero, and how division should round. Also check that a token such as -7 counts as a number. A check like "starts with a minus sign" would wrongly treat it as the subtraction operator.

Why it is asked

Postfix evaluation is the simplest real use of a stack: the most recent results are exactly the ones the next operator needs. Interviewers use it to check that you pick the stack without being told, that you get operand order right for the operators where order matters, and that you know how your language rounds negative division. It also opens the door to bigger questions, like evaluating ordinary infix expressions with parentheses.

A slower way to see it

Without a stack, you can repeatedly find the first operator in the list, apply it to the two tokens just before it, and replace those three tokens with the result. Each pass shortens the list by two. Finding the operator and rebuilding the list costs O(n) per pass, and there are about n/2 passes, so the total is O(n²). It is a useful picture, because it shows that each operator really does consume the two most recent values.

def apply(op, a, b):
    if op == "+": return a + b
    if op == "-": return a - b
    if op == "*": return a * b
    q = abs(a) // abs(b)
    return q if (a < 0) == (b < 0) else -q

def evaluate_by_collapsing(tokens):
    items = list(tokens)
    while len(items) > 1:
        i = next(j for j, t in enumerate(items) if t in "+-*/" and len(t) == 1)
        value = apply(items[i], int(items[i - 2]), int(items[i - 1]))
        items[i - 2:i + 1] = [str(value)]
    return int(items[0])
Collapse the leftmost operator until one value remains. O(n²).

The stack evaluator

The collapsing approach keeps searching for work. A stack hands the operands over directly. Push every number. On an operator, pop twice: the first pop is the right operand and the second is the left, since the right operand was pushed later. Apply the operator and push the result back so a later operator can use it. A valid expression leaves exactly one value on the stack.

def divide_toward_zero(a, b):
    q = abs(a) // abs(b)
    return q if (a < 0) == (b < 0) else -q

OPS = {
    "+": lambda a, b: a + b,
    "-": lambda a, b: a - b,
    "*": lambda a, b: a * b,
    "/": divide_toward_zero,
}

def evaluate_postfix(tokens):
    stack = []
    for token in tokens:
        if token in OPS:
            right = stack.pop()
            left = stack.pop()
            stack.append(OPS[token](left, right))
        else:
            stack.append(int(token))
    return stack[0]
Python: one pass with a dict of operator functions. O(n) time, O(n) space.

The helper exists because Python's // rounds toward negative infinity, so -7 // 2 is -4 where the problem expects -3. Dividing absolute values and restoring the sign avoids that. You will also see int(a / b) in many solutions. It gives the same answers for ordinary sizes, but it goes through a float, which can lose precision for very large integers. Either is fine if you say why you chose it.

function evaluatePostfix(tokens) {
  const stack = [];
  for (const token of tokens) {
    if (token === "+" || token === "-" || token === "*" || token === "/") {
      const right = stack.pop();
      const left = stack.pop();
      if (token === "+") stack.push(left + right);
      else if (token === "-") stack.push(left - right);
      else if (token === "*") stack.push(left * right);
      else stack.push(Math.trunc(left / right));
    } else {
      stack.push(Number(token));
    }
  }
  return stack[0];
}
JavaScript: Math.trunc gives truncation toward zero directly.

JavaScript numbers are floating point, so Math.trunc(left / right) matches integer truncation as long as values stay within the safe integer range. For results that could grow beyond that, switch to BigInt, where / already truncates toward zero.

Complexity

n is the number of tokens
ApproachTimeExtra space
Collapse the leftmost operator repeatedlyO(n²)O(n) for the working copy
Recursive evaluation from the endO(n)O(n) call stack
Stack, one passO(n)O(n) in the worst case
n is the number of tokens. Scroll sideways on a small screen.

The stack's worst case is a long run of numbers followed by a long run of operators, such as 1 2 3 4 + + +, where every number sits on the stack at once.

Inputs that catch people out

  • A negative number token like -7, which must be parsed as a number rather than read as an operator.
  • Negative division such as -7 2 / or 7 -2 /, where floor and truncation disagree.
  • A single number with no operators: the answer is that number.
  • Subtraction and division with operands swapped by mistake, which an input made only of additions and multiplications will never reveal but 7 2 5 - / will.
  • Large intermediate products, if your language has fixed-width integers.

Common errors

  • Popping into a, b and computing a - b, which reverses the operands.
  • Using Python's // and passing every test that only has positive numbers.
  • Checking token.isdigit() to detect numbers, which returns false for -7.
  • Reaching for eval on a rebuilt string. It skips the point of the exercise and invites injection questions.

Follow-ups

  • Validate the input instead of trusting it. Fail if an operator finds fewer than two values or the stack does not end with exactly one.
  • Add more operators. Keep the operator table; a unary operator such as negation pops one value instead of two.
  • Convert infix to postfix first. That is the shunting-yard algorithm, which uses a stack of operators and precedence rules.
  • Evaluate infix directly with parentheses. Use two stacks, one for numbers and one for operators, or recursive descent.

Explaining it out loud

Fictional example

One way to narrate the solution
Candidate
In postfix, every operator works on the two values produced just before it, so a stack is the natural place to keep pending values.
Candidate
Numbers get pushed. For an operator I pop the right operand first, then the left, compute, and push the result. At the end one value remains.
Candidate
Division should truncate toward zero. Python's floor division doesn't, so I divide absolute values and fix the sign. Linear time, linear space.

Next problems

Min Stack adds a running minimum to the same structure, and Generate Parentheses builds balanced expressions rather than reading them. Valid Parentheses is the matching-brackets cousin, and the coding problems hub has the full list by pattern.

Rehearsing with Natively

Natively runs on Mac and Windows. Point it at this problem with a screenshot while you practice and it can explain why the stack fits and flag the negative-division case before you test it. It also keeps a transcript of the mock, which helps you spot whether you swapped the operands silently or said it out loud. See the AI interview assistant for how practice sessions are saved.

Questions people ask

How do you evaluate Reverse Polish Notation?

Scan the tokens with a stack. Push numbers; for an operator, pop the right operand, then the left, apply the operator and push the result. The last value on the stack is the answer, in O(n) time.

Why does my Python RPN solution fail on negative division?

Python's // operator rounds toward negative infinity, so -7 // 2 is -4. The problem expects truncation toward zero, which gives -3. Divide absolute values and restore the sign, or use int(a / b) for ordinary sizes.

Which operand is popped first in postfix evaluation?

The right operand, because it was pushed last. Popping into the wrong order only shows up with subtraction and division, so test with those.

What is the time and space complexity of Evaluate Reverse Polish Notation?

O(n) time for one pass over the tokens and O(n) space in the worst case, when many numbers are pushed before any operator appears.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP