150NeetCode 150

23.Evaluate Reverse Polish Notation

MediumStack ยท 3/7

Problem

You are given an array of strings tokens describing an arithmetic expression in Reverse Polish Notation (postfix): every operator comes after its two operands. Evaluate the expression and return its integer value.

  • Valid operators are +, -, * and /.
  • Each operand is an integer (it may be negative).
  • Division truncates toward zero.
  • The input is always a valid expression, there is no division by zero, and every intermediate result fits in a 32-bit integer.

Examples

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

Constraints

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

๐Ÿ’ก Key Insight

In postfix notation, an operator always applies to the two most recently produced values. A stack holds exactly those: push numbers; on an operator, pop two values, combine them, and push the result back. Mind the order โ€” the first value popped is the right operand.

Brute Force (Repeated Reduction)

TimeO(nยฒ)SpaceO(n)

Intuition

Find the first operator in the list. The two tokens immediately before it are guaranteed to be numbers (otherwise a previous operator would come first). Replace those three tokens with their result and repeat until a single number remains.

Algorithm

  1. Copy tokens into a mutable list.
  2. While the list has more than one element:
    • Find the first index i holding an operator.
    • Compute list[i-2] op list[i-1].
    • Replace positions i-2..i with the result.
  3. Return the single remaining value.

Visualization

[2, 1, +, 3, *]
       ^ first operator โ†’ 2 + 1 = 3
[3, 3, *]
       ^ โ†’ 3 * 3 = 9
[9] โ†’ answer 9

Code

java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public int evalRPN(String[] tokens) {
        List<String> list = new ArrayList<>(Arrays.asList(tokens));
        while (list.size() > 1) {
            int i = 0;
            while (!isOperator(list.get(i))) {
                i++; // first operator in the list
            }
            int a = Integer.parseInt(list.get(i - 2));
            int b = Integer.parseInt(list.get(i - 1));
            int result = apply(a, b, list.get(i));
            // replace "a b op" with the result
            list.remove(i);
            list.remove(i - 1);
            list.set(i - 2, String.valueOf(result));
        }
        return Integer.parseInt(list.get(0));
    }

    private boolean isOperator(String t) {
        return t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/");
    }

    private int apply(int a, int b, String op) {
        switch (op) {
            case "+": return a + b;
            case "-": return a - b;
            case "*": return a * b;
            default:  return a / b; // Java truncates toward zero
        }
    }
}

Complexity

  • Time: O(nยฒ) โ€” up to n / 2 reductions, each scanning and shifting an ArrayList.
  • Space: O(n) โ€” the mutable copy.

Complexity Comparison

Approach Time Space
Brute Force (repeated reduction) O(nยฒ) O(n)
Recursion from the end O(n) O(n)
Stack O(n) O(n)

Common Pitfalls

  • Popping operands in the wrong order for - and /: the first pop is the right operand (a - b, not b - a).
  • Detecting operators with t.charAt(0) == '-' โ€” negative numbers like "-11" also start with '-'; compare the whole string (or check length 1).
  • Using Math.floorDiv โ€” the problem wants truncation toward zero, which is what plain / does in Java (-7 / 2 == -3).
  • Comparing strings with == instead of equals (the switch on String uses equals under the hood).