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:
The brute force approach to evaluating Reverse Polish Notation expressions involves directly processing the provided expression step by step. It operates by reading each element and immediately acting upon it, using a simple mechanism to keep track of intermediate results. It's a very literal interpretation of the expression's structure.
Here's how the algorithm would work step-by-step:
def evaluate_reverse_polish_notation_brute_force(tokens):
number_stack = []
for token in tokens:
if token.isdigit() or (token.startswith('-') and token[1:].isdigit()):
number_stack.append(int(token))
else:
#If it is not a number, we assume it is an operator
operand_2 = number_stack.pop()
operand_1 = number_stack.pop()
if token == '+':
result = operand_1 + operand_2
elif token == '-':
result = operand_1 - operand_2
elif token == '*':
result = operand_1 * operand_2
else:
# Integer division toward zero
result = int(operand_1 / operand_2)
# Store the intermediate result back on the stack.
number_stack.append(result)
#The final result is the only thing left on the stack.
return number_stack[0]This problem involves evaluating a mathematical expression written in a specific format. The optimal approach uses a 'last in, first out' data structure to keep track of numbers and perform operations in the correct order.
Here's how the algorithm would work step-by-step:
def evaluate_reverse_polish_notation(tokens):
number_stack = []
for token in tokens:
if token in ('+', '-', '*', '/'):
# Ensure operations are done in correct order
operand_2 = number_stack.pop()
operand_1 = number_stack.pop()
if token == '+':
result = operand_1 + operand_2
elif token == '-':
result = operand_1 - operand_2
elif token == '*':
result = operand_1 * operand_2
else:
# Integer division as per problem description
result = int(operand_1 / operand_2)
# Push the result back onto the stack
number_stack.append(result)
else:
# Convert string to integer and push onto the stack
number_stack.append(int(token))
# The final result is the only item left on the stack
return number_stack.pop()| Case | How to Handle |
|---|---|
| Null or empty input array | Return 0 or throw an IllegalArgumentException since there's nothing to evaluate. |
| Array contains non-string elements | Throw an IllegalArgumentException since only string tokens are expected. |
| Array contains invalid operators (e.g., '%', '$') | Throw an IllegalArgumentException as these are not valid Reverse Polish Notation operators. |
| Division by zero | Throw an ArithmeticException or return positive/negative infinity based on the specific problem requirements. |
| Integer overflow/underflow during calculations | Use a larger data type (like long) or check for overflow/underflow before performing the operation to prevent errors. |
| Single element array with a non-numeric string | Attempt to convert the string to an integer and throw NumberFormatException if it fails. |
| Input leads to a non-integer result (division producing a float) | Cast the result to an integer according to the problem specifications (truncation or rounding). |
| Insufficient operands in the expression | Throw an IllegalArgumentException when encountering an operator without enough preceding operands in the stack. |