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:
'+', '-', '*', and '/'.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 <= 104tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].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:
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:
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])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:
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()| Case | How to Handle |
|---|---|
| Single element array containing only a number | The loop finishes without operations and returns that single parsed integer from the stack. |
| Division by zero | The algorithm will naturally throw a runtime arithmetic exception when attempting to divide by zero. |
| Negative operands and negative division truncation | 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 | Using larger integer types like 64-bit integers prevents overflow issues during intermediate arithmetic computations. |
| Invalid RPN expression with missing operators | The stack will contain more than one element at the end of execution, indicating a malformed input. |
| Invalid RPN expression with missing operands | The stack will underflow when attempting to pop operands for an operator, signaling an invalid expression. |
| Maximum constraint array size | The linear time stack-based approach scales efficiently and processes large token arrays within time limits. |