15% off all plans & roadmaps Use code

See plans

Evaluate Reverse Polish Notation

Updated

TL;DR: Evaluate a postfix expression given as string tokens. Push numbers on a stack, and when an operator appears, pop two values, apply it, and push the result back.

Problem

You are given an array of strings tokens that holds an arithmetic expression written in Reverse Polish Notation (postfix form). Evaluate the expression and return its value as an integer.

Keep these rules in mind:

  • The valid operators are +, -, *, and /.
  • Each operand is either an integer or the result of another sub-expression.
  • Division between two integers always truncates toward zero.
  • No expression divides by zero.
  • The input is always a valid postfix expression.
  • The final answer and every intermediate result fit in a 32-bit integer.

Example 1

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3

Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

Constraints

  • 1 <= tokens.length <= 10^4
  • tokens[i] is either an operator ("+", "-", "*", "/") or an integer in the range [-200, 200].

Constraints that matter

  • tokens.length up to 10^4 means an O(n^2) rescan is only tens of millions of steps, which is survivable but wasteful. A single O(n) pass is the target.
  • Tokens like -11 are numbers, not operators. You must test the whole token, not its first character.
  • Division truncates toward zero. Python's // floors, so -6 // 132 gives -1 and is wrong here.
  • The input is always valid and never divides by zero, so you do not need to guard against an empty stack or a zero divisor.
  • Every intermediate value fits in 32 bits, so plain int is safe in Java, C++ and C# and no big-number handling is needed.

View on LeetCode

Hints

Hint 1

This is the Stack pattern for expression evaluation.

Hint 2

Treat the token list as an expression you shrink in place.

Solution

Intuition

This is the Stack pattern for expression evaluation. In postfix notation the operator comes after its two operands, so you never need parentheses or precedence rules. The order of the tokens already encodes the order of the work.

Picture a stack of plates in a kitchen: each finished dish goes on top, and when a meal needs two things, you take the two plates on top. The stack is the set of unused values, and each operator consumes the top two and puts its result back.

Look at what an operator needs: the two most recent values that nobody has used yet. That is last-in, first-out behavior. A number you read cannot be used until you see its operator, so you park it. When an operator arrives, the top two parked values are exactly its operands.

The stack always holds finished sub-results that are waiting for a later operator. After you apply an operator, its result goes back on top, ready to be an operand for the next one. Because the input is valid, the stack ends with exactly one value, the answer.

One detail decides most wrong answers. The first value you pop is the right operand, and the second is the left. For + and * the order does not matter. For - and / it does.

Watch the pattern animation

Worked example

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: The / token works on 13 and 5 and gives 2, because 13 / 5 = 2.6 truncates to 2. The + token then adds 4 and 2 to give 6. In infix form the expression is 4 + (13 / 5).

Approach 1: Brute force: rescan and collapse

Treat the token list as an expression you shrink in place. Find the first operator, take the two tokens before it, compute the result, and replace those three tokens with one token holding the result. Repeat until one token is left.

This works because the first operator in the list always has two plain numbers right before it. Everything to its left is a number, so nothing earlier can be reduced first.

Steps

  1. Copy tokens into a mutable list.
  2. While the list has more than one token, scan from index 0 to find the first operator at index i.
  3. Parse the tokens at i - 2 and i - 1 as integers a and b.
  4. Compute a op b, truncating division toward zero.
  5. Replace the three tokens at i - 2, i - 1, i with the result as a string.
  6. When one token remains, parse it and return it.

Dry run

Start with [4, 13, 5, /, +].

  • Pass 1: the first operator is / at index 3. The operands are 13 and 5. The result is 2. The list becomes [4, 2, +].
  • Pass 2: the first operator is + at index 2. The operands are 4 and 2. The result is 6. The list becomes [6].
  • One token is left, so the answer is 6.

Complexity

TimeO(n^2)
SpaceO(n)

Let n be the number of tokens. A valid expression has about n / 2 operators, so the loop runs about n / 2 times. Each pass scans up to n tokens to find an operator and shifts up to n tokens when it deletes two of them, so a pass costs O(n). That gives O(n^2) in total, and the copied list uses O(n) space.

PythonTested in our runner

from typing import List

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        ops = {"+", "-", "*", "/"}
        arr = list(tokens)
        while len(arr) > 1:
            i = 0
            while arr[i] not in ops:
                i += 1
            a, b = int(arr[i - 2]), int(arr[i - 1])
            if arr[i] == "+":
                r = a + b
            elif arr[i] == "-":
                r = a - b
            elif arr[i] == "*":
                r = a * b
            else:
                r = int(a / b)  # truncate toward zero
            arr[i - 2:i + 1] = [str(r)]
        return int(arr[0])

Approach 2: Single pass with prev links

What's slow: every pass rescans from index 0 and shifts the array after each deletion. The scan is repeated work, because operators are already in the order you need to process them. The shifting is repeated work too, because you only need to know which earlier slot holds each operand.

The insight that fixes it: walk the tokens once, left to right, and give each slot a prev link to the nearest unused value on its left. When you reach an operator, its operands sit at prev[i] and prev[prev[i]]. Compute the result into the operator's own slot, then point prev[i] past both operands. Nothing is ever moved, so deletion costs O(1).

Steps

  1. Create vals of length n and prev where prev[i] = i - 1.
  2. For each index i, if the token is a number, store its integer in vals[i].
  3. If it is an operator, set right = prev[i] and left = prev[right].
  4. Compute vals[left] op vals[right] and store it in vals[i].
  5. Set prev[i] = prev[left] so the two operands are skipped from now on.
  6. After the loop, return vals[n - 1], because the last token is the root of the expression.

Dry run

Tokens are [4, 13, 5, /, +] at indices 0 to 4. Start with prev = [-1, 0, 1, 2, 3] and vals = [4, 13, 5, ?, ?].

  • i = 3 (/): right = prev[3] = 2, left = prev[2] = 1. vals[3] = 13 / 5 = 2. Set prev[3] = prev[1] = 0.
  • i = 4 (+): right = prev[4] = 3, left = prev[3] = 0. vals[4] = 4 + 2 = 6. Set prev[4] = prev[0] = -1.
  • Return vals[4] = 6.

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of tokens. The loop visits each index once and does a fixed number of array reads, one arithmetic operation and one link update per index, so time is O(n). The vals and prev arrays each hold n entries, so space is O(n). This is the stack idea in disguise: the chain of prev links is the stack.

PythonTested in our runner

from typing import List

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        n = len(tokens)
        vals = [0] * n
        prev = list(range(-1, n - 1))
        for i, t in enumerate(tokens):
            if t in ("+", "-", "*", "/"):
                right = prev[i]
                left = prev[right]
                a, b = vals[left], vals[right]
                if t == "+":
                    vals[i] = a + b
                elif t == "-":
                    vals[i] = a - b
                elif t == "*":
                    vals[i] = a * b
                else:
                    vals[i] = int(a / b)
                prev[i] = prev[left]  # skip both operands
            else:
                vals[i] = int(t)
        return vals[n - 1]
Expression Evaluation (RPN/Infix) pattern infographic for Evaluate Reverse Polish Notation

Solution pattern

Expression Evaluation (RPN/Infix)

Part of Stack Patterns

Approach 3: One-pass stackOptimalExpression Evaluation (RPN/Infix)

What's slow: nothing in time, since the previous approach is already O(n). What is clumsy is the bookkeeping. Two parallel arrays and index links describe a structure that a stack gives you directly.

The insight that fixes it: push each number onto a stack, and let each operator pop its two operands and push the result. The top of the stack is always the nearest unused value, which is what prev was tracking. You store only live values, so the stack holds at most the numbers still waiting for an operator.

Why it is correct. The stack always holds exactly the values that have been computed but not yet consumed, in the order they appear. Because each operator in postfix applies to the two most recent unused values, popping the top two gives its true operands. Valid input leaves a single value on the stack, which is the full expression result.

Steps

  1. Create an empty stack of integers.
  2. For each token, check whether it is exactly +, -, * or /.
  3. If it is a number, parse it and push it.
  4. If it is an operator, pop b first (right operand), then pop a (left operand).
  5. Compute a op b, with division truncating toward zero, and push the result.
  6. After the last token, the stack holds one value. Return it.

Dry run

Tokens are [4, 13, 5, /, +].

TokenActionStack after
4push 4[4]
13push 13[4, 13]
5push 5[4, 13, 5]
/pop b = 5, pop a = 13, push 13 / 5 = 2[4, 2]
+pop b = 2, pop a = 4, push 4 + 2 = 6[6]

The stack holds one value, 6, so the answer is 6.

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of tokens. Each token is processed once, and each push, pop and arithmetic step costs O(1), so time is O(n). Every number is pushed once and every operator removes one value net, so the stack never exceeds the count of numbers. In the worst case, such as 1 2 3 4 + + +, all numbers sit on the stack before any operator runs, so space is O(n).

PythonTested in our runner

from typing import List

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack: List[int] = []
        for token in tokens:
            if token in ("+", "-", "*", "/"):
                b = stack.pop()  # right operand comes off first
                a = stack.pop()
                if token == "+":
                    stack.append(a + b)
                elif token == "-":
                    stack.append(a - b)
                elif token == "*":
                    stack.append(a * b)
                else:
                    # // floors, so truncate with float division instead
                    stack.append(int(a / b))
            else:
                stack.append(int(token))
        return stack[0]

Common mistakes

  • Computing b - a or b / a because the first pop is the right operand. Name the pops b = pop() then a = pop() and compute a op b.
  • Using a // b in Python. It floors, so -6 // 132 is -1 where the answer is 0. Use int(a / b), which truncates toward zero.
  • Detecting a subtraction by token[0] == '-'. The token -11 starts with a minus sign and is a number. Compare the whole token against the four operator strings.
  • Parsing every token with int(token) before checking for an operator. int("+") raises an error. Test for an operator first and parse only in the number branch.
  • Returning stack[-1] without trusting the input, or adding extra empty-stack checks that change behavior. The input is valid, so exactly one value remains and stack[0] is the answer.
  • Deleting from the middle of a list to mimic collapsing the expression. Each deletion shifts the tail and the total becomes O(n^2). Keep the stack at its top end.

Edge cases

  • ["5"]: a single number with no operator returns 5.
  • ["3","-4","*"]: a negative operand gives -12. The token -4 must parse as a number.
  • ["7","-2","/"]: 7 / -2 is -3.5 and truncates to -3, not -4.
  • ["1","2","-"]: operand order matters, so the result is -1, not 1.
  • ["-1","5","/"]: -1 / 5 truncates to 0. In JavaScript, use | 0 so the result is 0 and not -0.
  • A long chain such as 5000 numbers followed by 4999 + tokens: the stack grows to 5000 entries and the sum stays within 32 bits.

Follow-ups interviewers ask

Can you evaluate it recursively instead of with a stack?
Yes. Start at the last token, which is the root operator. Recursively evaluate the right operand first, then the left, and combine them. It is O(n) time, but recursion depth can reach n, around 5000 for the largest inputs, so Python needs an iterative version or a raised limit.
How would you handle an infix expression like 2 + 3 * 4 instead?
Convert it to postfix with the shunting-yard algorithm, which uses an operator stack and precedence rules, then run the stack evaluator above. You can also evaluate directly with one stack for numbers and one for operators. Parentheses push and pop that operator stack.
How would you detect an invalid expression?
Check the stack size. An operator that finds fewer than two values means too many operators. A final stack size other than one means too many operands. Also reject unknown tokens and watch for division by zero before dividing.

Evaluate Reverse Polish Notation FAQ

What is the time complexity of Evaluate Reverse Polish Notation?

The stack solution is O(n) time and O(n) space, where n is the number of tokens. Each token is read once and costs a constant number of push, pop and arithmetic steps. The brute force rescan version is O(n^2).

Why use a stack for Evaluate Reverse Polish Notation?

An operator always applies to the two most recent unused values, which is last-in, first-out access. A stack gives you those values in O(1) and stores each result for the next operator. No precedence logic is needed.

How do you handle division in Evaluate Reverse Polish Notation in Python?

Use int(a / b) instead of a // b. Floor division rounds toward negative infinity, so negative quotients come out one too small. Java, C++, Go and C# already truncate toward zero with /. In JavaScript use Math.trunc or | 0.

Can Evaluate Reverse Polish Notation be solved in O(1) extra space?

Not in general. An expression like 1 2 3 4 + + + needs all four numbers held until the first operator appears, so the live values grow with n. You can reuse the input array as the stack to avoid a second structure, but that is still O(n) storage, kept in place.

Which operand is the left one when an operator pops two values?

The second value popped is the left operand and the first value popped is the right operand. For ["4","13","5","/"] the pops return 5 then 13, so the computation is 13 / 5. Reversing them gives 5 / 13 = 0.

Why is a token like -11 not treated as an operator in LeetCode 150?

Operators are single-character tokens equal to +, -, * or /. The token -11 has length 3 and parses as an integer. Compare the full token against the operator set instead of looking at its first character.

Asked at

See which companies ask this — Pro

Practise it