KatInterview

150. Evaluate Reverse Polish Notation

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Stack-based Evaluation

This approach uses a stack to evaluate the expression, which is the standard and most intuitive way to handle Reverse Polish Notation (RPN).

Solution

Evaluate Reverse Polish Notation in Python

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        # Use a list as a stack to store operands.
        stack = []

        for token in tokens:
            if token == '+':
                # Pop the second operand, then the first.
                op2 = stack.pop()
                op1 = stack.pop()
                stack.append(op1 + op2)
            elif token == '-':
                op2 = stack.pop()
                op1 = stack.pop()
                stack.append(op1 - op2)
            elif token == '*':
                op2 = stack.pop()
                op1 = stack.pop()
                stack.append(op1 * op2)
            elif token == '/':
                op2 = stack.pop()
                op1 = stack.pop()
                # Division must truncate toward zero.
                # int(op1 / op2) achieves this correctly for both positive and negative results.
                # e.g., int(6 / -132) -> 0, int(-10 / 3) -> -3
                stack.append(int(op1 / op2))
            else:
                # If it's a number, convert to int and push to the stack.
                stack.append(int(token))
        
        # The final result is the only element in the stack.
        return stack[0]

Evaluate Reverse Polish Notation in Java

class Solution {
    public int evalRPN(String[] tokens) {
        // Use a stack to store the operands.
        Stack<Integer> stack = new Stack<>();

        for (String token : tokens) {
            // Check if the token is an operator.
            if (token.equals("+")) {
                // Pop the top two operands for addition.
                int op2 = stack.pop();
                int op1 = stack.pop();
                stack.push(op1 + op2);
            } else if (token.equals("-")) {
                // For subtraction, order matters: op1 - op2.
                int op2 = stack.pop();
                int op1 = stack.pop();
                stack.push(op1 - op2);
            } else if (token.equals("*")) {
                // Pop operands for multiplication.
                int op2 = stack.pop();
                int op1 = stack.pop();
                stack.push(op1 * op2);
            } else if (token.equals("/")) {
                // For division, order matters: op1 / op2.
                // Java's integer division truncates towards zero.
                int op2 = stack.pop();
                int op1 = stack.pop();
                stack.push(op1 / op2);
            } else {
                // If the token is a number, parse it and push it onto the stack.
                stack.push(Integer.parseInt(token));
            }
        }

        // The final result is the only element remaining on the stack.
        return stack.pop();
    }
}

Evaluate Reverse Polish Notation in C++

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        // Use a stack to store operands.
        stack<long> s;
        
        for (const string& token : tokens) {
            if (token == "+") {
                // Pop the top two operands, perform addition, and push the result back.
                long op2 = s.top(); s.pop();
                long op1 = s.top(); s.pop();
                s.push(op1 + op2);
            } else if (token == "-") {
                // Pop operands, perform subtraction (op1 - op2), and push result.
                long op2 = s.top(); s.pop();
                long op1 = s.top(); s.pop();
                s.push(op1 - op2);
            } else if (token == "*") {
                // Pop operands, perform multiplication, and push result.
                long op2 = s.top(); s.pop();
                long op1 = s.top(); s.pop();
                s.push(op1 * op2);
            } else if (token == "/") {
                // Pop operands, perform division (op1 / op2), and push result.
                // C++ integer division truncates toward zero, as required.
                long op2 = s.top(); s.pop();
                long op1 = s.top(); s.pop();
                s.push(op1 / op2);
            } else {
                // If it's a number, convert it to long and push onto the stack.
                s.push(stol(token));
            }
        }
        
        // The final result is the only element left in the stack.
        return s.top();
    }
};

Evaluate Reverse Polish Notation in TypeScript

function evalRPN(tokens: string[]): number {
    // Use an array as a stack to store operands.
    const stack: number[] = [];

    for (const token of tokens) {
        if (token === '+') {
            // Pop the second operand first, then the first.
            const op2 = stack.pop()!;
            const op1 = stack.pop()!;
            stack.push(op1 + op2);
        } else if (token === '-') {
            const op2 = stack.pop()!;
            const op1 = stack.pop()!;
            stack.push(op1 - op2);
        } else if (token === '*') {
            const op2 = stack.pop()!;
            const op1 = stack.pop()!;
            stack.push(op1 * op2);
        } else if (token === '/') {
            const op2 = stack.pop()!;
            const op1 = stack.pop()!;
            // Use Math.trunc() to ensure division truncates toward zero.
            stack.push(Math.trunc(op1 / op2));
        } else {
            // If it's a number, parse it and push onto the stack.
            stack.push(parseInt(token, 10));
        }
    }

    // The final result is the only element remaining in the stack.
    return stack[0];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.