Logo for ammarahmed.ca
Medium
May 27, 2025
#stack
#math

150. Evaluate Reverse Polish Notation

Problem

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:

  • The valid operators are '+', '-', '*', and '/'.
    • Each operand may be an integer or another expression.
      • The division between two integers always truncates toward zero.
        • There will not be any division by zero.
          • The input represents a valid arithmetic expression in a reverse polish notation.
            • The answer and all the intermediate calculations can be represented in a 32-bit integer.

              Example 1:

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

              Example 2:

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

              Example 3:

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

              Constraints:

              • 1 <= tokens.length <= 104
                • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].

                  Approach

                  This is a very interesting problem. We can use a stack to solve this problem.

                  The general idea is that whenever we see an operator, we want to use it to evaluate the last two elements and add the result back to our evaluation line.

                  Let's take the first example: [2, 1, +, 3, *]. We'll go iteration by iteration, displaying our stack.

                  • i = 0, value = 2, stack = [2]
                    • i = 1, value = 1, stack = [2, 1]
                      • i = 2, value = +, stack = [3]
                        • i = 3, value = 3, stack = [3, 3]
                          • i = 4, value = *, stack = [9]

                            Once we complete the iterations, we can simply return the last value in the stack.

                            For my specific solution, I wrote a helper function to do the evaluation. An important note is on the order of evaluation specifically for subtraction and division. We want to do b - a and b / a, where a is the first value popped and b is the second value popped.

                            Complexity

                            Time: O(n)

                            We iterate through the tokens only once.

                            Space: O(1)

                            No extra space is created.

                            Solution

                            1import "strconv" 2 3func eval(a, b int, op string) int { 4 if op == "+" { 5 return a + b 6 } else if op == "*" { 7 return a * b 8 } else if op == "-" { 9 return b - a 10 } else { 11 return b / a 12 } 13} 14 15func evalRPN(tokens []string) int { 16 stack := []int{} 17 for _, s := range tokens { 18 if s == "+" || s == "*" || s == "-" || s == "/" { 19 // evaluate 20 var a, b int 21 a, stack = stack[len(stack)-1], stack[:len(stack)-1] 22 b, stack = stack[len(stack)-1], stack[:len(stack)-1] 23 stack = append(stack, eval(a, b, s)) 24 } else { 25 num, _ := strconv.Atoi(s) 26 stack = append(stack, num) 27 } 28 } 29 30 return stack[len(stack)-1] 31} 32