Taro Logo

Evaluate Reverse Polish Notation

#236 Most AskedMedium
0 views
Topics:
Stacks

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:

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 <= 104
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected behavior for division when it results in a non-integer, and should we truncate towards zero?
  2. Is it guaranteed that the input expression is always valid and will always result in a single integer value?
  3. What should be returned if the input array of tokens is empty?
  4. Can the intermediate values or the final result exceed the standard 32-bit integer limits, requiring us to handle potential overflow?
  5. Are all tokens guaranteed to be valid operators or valid integers, or could there be malformed inputs like invalid strings?

Brute Force Solution

Approach

Imagine you are solving a giant puzzle made of numbers and math symbols written in a special backward order. The brute force approach involves constantly scanning the entire list from the beginning to find the very next pair of numbers followed by a math symbol, performing that single calculation, and rewriting the list with the new answer.

Here's how the algorithm would work step-by-step:

  1. Look at the list of numbers and symbols from left to right to find the first place where a math symbol appears right after two numbers.
  2. Perform the math operation on those two numbers immediately.
  3. Erase those two numbers and the symbol from the list, and write the single answer in their exact spot.
  4. Take this newly updated list and repeat the entire search process from the beginning.
  5. Continue this cycle of searching, calculating, and shrinking the list until only one single number remains.
  6. Declare that final remaining number as the grand total for the whole puzzle.

Code Implementation

def evalRPN(tokens): 
    expression_tokens = list(tokens)

    # We repeatedly scan the list to find the first operator following two numbers
    while len(expression_tokens) > 1:
        target_index = 0
        
        while target_index < len(expression_tokens):
            if expression_tokens[target_index] in {"+", "-", "*", "/"}:
                break
                
            target_index += 1

        # Extract the two operands preceding the operator to perform calculation
        first_operand = int(expression_tokens[target_index - 2])
        second_operand = int(expression_tokens[target_index - 1])
        operator_symbol = expression_tokens[target_index]

        if operator_symbol == "+":
            calculation_result = first_operand + second_operand
        elif operator_symbol == "-":
            calculation_result = first_operand - second_operand
        elif operator_symbol == "*":
            calculation_result = first_operand * second_operand
        else:
            calculation_result = int(first_operand / second_operand)

        # Replace the evaluated components with the single computed result
        expression_tokens[target_index - 2:target_index + 1] = [str(calculation_result)]

    return int(expression_tokens[0])

Big(O) Analysis

Time Complexity
O(n²) – For each of the n tokens in the list, the brute force approach repeatedly scans from the beginning to find a math symbol preceded by two numbers. Since each operation shrinks the list and requires restarting the search, finding and processing the operations takes roughly n steps for each of the n elements. This leads to approximately n * n/2 operations in the worst case, which simplifies to O(n²).
Space Complexity
O(n) – The algorithm relies on an explicit stack data structure to hold intermediate numbers as it scans the token list from left to right. In the worst-case scenario where the expression consists mostly of numbers followed by operators at the very end, this stack will store up to N items. Therefore, the auxiliary space grows linearly with respect to N, the total number of elements in the input list.

Optimal Solution

Approach

The optimal strategy is to process the list of numbers and math symbols sequentially using a memory pile. Whenever you see a number, you set it aside on the pile, and whenever you see a math symbol, you combine the most recent numbers on the pile using that symbol.

Here's how the algorithm would work step-by-step:

  1. Create an empty memory pile to hold numbers as you encounter them.
  2. Look at the list of items one by one, moving from left to right.
  3. If the item is a plain number, pick it up and place it on top of your memory pile.
  4. If the item is a math symbol, take the top two numbers off your memory pile.
  5. Perform the math operation using those two numbers, keeping the correct order in mind.
  6. Place the resulting single answer back onto the top of your memory pile.
  7. Continue this process until you have looked at every item in the list.
  8. At the very end, the single number left sitting on your memory pile is the final answer.

Code Implementation

class Solution:
    def evalRPN(self, tokens: list[str]) -> int:
        memory_pile = []

        for token in tokens:
            if token == "+":
                # We pop twice because operators require exactly two operands in RPN.
                right_operand = memory_pile.pop()
                left_operand = memory_pile.pop()
                memory_pile.append(left_operand + right_operand)
            elif token == "-":
                right_operand = memory_pile.pop()
                left_operand = memory_pile.pop()
                memory_pile.append(left_operand - right_operand)
            elif token == "*":
                right_operand = memory_pile.pop()
                left_operand = memory_pile.pop()
                memory_pile.append(left_operand * right_operand)
            elif token == "/":
                # Truncation toward zero is required for integer division in this problem.
                right_operand = memory_pile.pop()
                left_operand = memory_pile.pop()
                memory_pile.append(int(left_operand / right_operand))
            else:
                # Numbers are pushed onto the pile to be consumed by upcoming operators.
                memory_pile.append(int(token))

        return memory_pile.pop()

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of items in the list of numbers and math symbols. We iterate through this list of n items exactly once, from left to right. During this single pass, pushing to and popping from our memory pile takes constant time per item. Therefore, the total operations scale linearly with n, simplifying to O(n).
Space Complexity
O(N) – The auxiliary data structure driving the space usage is the memory pile, implemented as a stack to hold numbers as we scan the input from left to right. In the worst-case scenario where the expression consists entirely of numbers before any math symbols, the stack will store up to N items. Therefore, the extra memory required scales linearly with the input size N, leading to an auxiliary space complexity of O(N).

Edge Cases

Single element array containing only a number
How to Handle:
The loop finishes without operations and returns that single parsed integer from the stack.
Division by zero
How to Handle:
The algorithm will naturally throw a runtime arithmetic exception when attempting to divide by zero.
Negative operands and negative division truncation
How to Handle:
Language-specific integer division must truncate toward zero rather than floor, which standard division operators in languages like C++ and Java handle automatically.
Integer overflow during multiplication or addition
How to Handle:
Using larger integer types like 64-bit integers prevents overflow issues during intermediate arithmetic computations.
Invalid RPN expression with missing operators
How to Handle:
The stack will contain more than one element at the end of execution, indicating a malformed input.
Invalid RPN expression with missing operands
How to Handle:
The stack will underflow when attempting to pop operands for an operator, signaling an invalid expression.
Maximum constraint array size
How to Handle:
The linear time stack-based approach scales efficiently and processes large token arrays within time limits.
0/257 completed