150. Evaluate Reverse Polish Notation

Medium

Problem Description

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

Examples

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
Jump to Solution: Python Java C++ JavaScript C#

Python Solution


def evalRPN(tokens: List[str]) -> int:
    stack = []
    operators = {
        '+': lambda x, y: x + y,
        '-': lambda x, y: x - y,
        '*': lambda x, y: x * y,
        '/': lambda x, y: int(x / y)  # truncate toward zero
    }
    
    for token in tokens:
        if token in operators:
            b = stack.pop()
            a = stack.pop()
            stack.append(operators[token](a, b))
        else:
            stack.append(int(token))
    
    return stack[0]

Java Solution


class Solution {
    public int evalRPN(String[] tokens) {
        Stack stack = new Stack<>();
        
        for (String token : tokens) {
            if (token.equals("+")) {
                stack.push(stack.pop() + stack.pop());
            } else if (token.equals("-")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a - b);
            } else if (token.equals("*")) {
                stack.push(stack.pop() * stack.pop());
            } else if (token.equals("/")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a / b);
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        
        return stack.pop();
    }
}

C++ Solution


class Solution {
public:
    int evalRPN(vector& tokens) {
        stack stack;
        
        for (const string& token : tokens) {
            if (token == "+" || token == "-" || token == "*" || token == "/") {
                int b = stack.top(); stack.pop();
                int a = stack.top(); stack.pop();
                
                if (token == "+") stack.push(a + b);
                else if (token == "-") stack.push(a - b);
                else if (token == "*") stack.push(a * b);
                else if (token == "/") stack.push(a / b);
            } else {
                stack.push(stoi(token));
            }
        }
        
        return stack.top();
    }
};

JavaScript Solution


/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function(tokens) {
    const stack = [];
    const operators = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => Math.trunc(a / b)  // truncate toward zero
    };
    
    for (const token of tokens) {
        if (token in operators) {
            const b = stack.pop();
            const a = stack.pop();
            stack.push(operators[token](a, b));
        } else {
            stack.push(Number(token));
        }
    }
    
    return stack[0];
};

C# Solution


public class Solution {
    public int EvalRPN(string[] tokens) {
        Stack stack = new Stack();
        
        foreach (string token in tokens) {
            if (token == "+") {
                stack.Push(stack.Pop() + stack.Pop());
            } else if (token == "-") {
                int b = stack.Pop();
                int a = stack.Pop();
                stack.Push(a - b);
            } else if (token == "*") {
                stack.Push(stack.Pop() * stack.Pop());
            } else if (token == "/") {
                int b = stack.Pop();
                int a = stack.Pop();
                stack.Push(a / b);
            } else {
                stack.Push(int.Parse(token));
            }
        }
        
        return stack.Pop();
    }
}

Complexity Analysis

Solution Explanation

This solution uses a stack to evaluate RPN expression:

Key points: