Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "3+2*2" Output: 7
Example 2:
Input: s = " 3/2 " Output: 1
Example 3:
Input: s = " 3+5 / 2 " Output: 5
Constraints:
1 <= s.length <= 3 * 105s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.s represents a valid expression.[0, 231 - 1].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 have a math expression written out on a long paper strip with numbers and basic signs like addition, subtraction, multiplication, and division. The brute force approach involves exploring every possible way to group and calculate different parts of the expression until you are left with a single final number.
Here's how the algorithm would work step-by-step:
def calculate(expression_string):
def parse_tokens(expression):
tokens_list = []
current_number = 0
# We iterate character by character to separate multi-digit numbers from operators
for character in expression:
if character.isdigit():
current_number = current_number * 10 + int(character)
elif character in "+-*/":
tokens_list.append(current_number)
tokens_list.append(character)
current_number = 0
tokens_list.append(current_number)
return tokens_list
def evaluate_expression(tokens):
if len(tokens) == 1:
return tokens[0]
# We explore all combinations by picking adjacent pairs to respect mathematical associativity
for index in range(1, len(tokens), 2):
operator = tokens[index]
left_operand = tokens[index - 1]
right_operand = tokens[index + 1]
if operator == '+':
sub_result = left_operand + right_operand
elif operator == '-':
sub_result = left_operand - right_operand
elif operator == '*':
sub_result = left_operand * right_operand
elif operator == '/':
sub_result = int(left_operand / right_operand)
new_tokens = tokens[:index - 1] + [sub_result] + tokens[index + 2:]
# We recursively attempt to reduce the remaining expression down to a single value
final_result = evaluate_expression(new_tokens)
if final_result is not None:
return final_result
cleaned_expression = expression_string.replace(" ", "")
initial_tokens = parse_tokens(cleaned_expression)
# We prioritize multiplication and division paths over addition and subtraction
operator_precedence_sorted_tokens = sorted(
[initial_tokens],
key=lambda current_tokens: any(operator in current_tokens for operator in ['*', '/']),
reverse=True
)
for candidate_tokens in operator_precedence_sorted_tokens:
evaluated_value = evaluate_expression(candidate_tokens)
if evaluated_value is not None:
return evaluated_value
return 0The optimal strategy is like keeping a running tally of math chunks, using a clever trick to handle multiplication and division immediately while saving addition and subtraction for the very end. By walking through the expression from left to right and remembering the most recent operation we saw, we can process everything cleanly in a single pass without getting confused by the order of operations.
Here's how the algorithm would work step-by-step:
def calculate(expression_string):
current_number = 0
previous_operator = '+'
number_stack = []
for character_index, character_value in enumerate(expression_string):
if character_value.isdigit():
current_number = (current_number * 10) + int(character_value)
if not character_value.isdigit() and character_value != ' ' or character_index == len(expression_string) - 1:
# Immediate execution of multiplication and division preserves the correct operator precedence.
if previous_operator == '+':
number_stack.append(current_number)
elif previous_operator == '-':
number_stack.append(-current_number)
elif previous_operator == '*':
previous_value = number_stack.pop()
number_stack.append(previous_value * current_number)
elif previous_operator == '/':
previous_value = number_stack.pop()
number_stack.append(int(previous_value / current_number))
previous_operator = character_value
current_number = 0
# Summing all accumulated values resolves the lower precedence addition and subtraction.
return sum(number_stack)| Case | How to Handle |
|---|---|
| Input string contains arbitrary spaces between numbers and operators | We must skip whitespace characters during iteration so they do not disrupt number parsing. |
| Multi-digit numbers spanning several characters | Accumulate consecutive digit characters into a running number variable before applying operators. |
| Precedence of multiplication and division over addition and subtraction | Use a stack to defer addition and subtraction while immediately executing multiplication and division with the last stack element. |
| Integer division with negative results truncating toward zero | Using standard integer division in languages like C++ or Java naturally truncates toward zero. |
| Single-element expressions containing only a non-negative integer | The loop processes the single number and pushes it to the stack, which then sums up to the correct value. |
| Expressions starting with a unary minus or plus sign | Treat the initial sign as operating against an implicit leading zero to correctly initialize the stack. |
| Maximum length expressions leading to intermediate value overflow | Ensure intermediate calculation variables use standard 32-bit or 64-bit signed integers to prevent overflow errors. |
| Division by zero within the expression | Assume valid problem constraints guarantee no division by zero will occur in the input. |