Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
The expression string represents a valid expression which follows the precedence of the arithmetic operators: parentheses have the highest precedence, followed by addition and subtraction.
Example 1:
Input: s = "1 + 1"
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
Constraints:
1 <= s.length <= 3 * 105s consists of digits, '+', '-', '(', ')', and ' '.s represents a valid expression.'+' is not used as a unary operation (as in "+1").'-' could be used as a unary operation (as in "-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 are given a long math puzzle written out as text with numbers, parentheses, and plus, minus, multiply, and divide signs. The brute force strategy involves testing every possible order of operations to see what number each different grouping produces until you find the final answer.
Here's how the algorithm would work step-by-step:
def calculate(expression):
cleaned_expression = expression.replace(" ", "")
if cleaned_expression.isdigit():
return int(cleaned_expression)
# Explore all possible evaluation orders by branching on every operator and set of parentheses
for index_position in range(len(cleaned_expression)):
current_character = cleaned_expression[index_position]
if current_character in "+-*/":
left_subexpression = cleaned_expression[:index_position]
right_subexpression = cleaned_expression[index_position + 1:]
left_val = calculate(left_subexpression)
right_val = calculate(right_subexpression)
if current_character == "+":
return left_val + right_val
elif current_character == "-":
return left_val - right_val
elif current_character == "*":
return left_val * right_val
elif current_character == "/":
return int(left_val / right_val)
# Handle expressions enclosed entirely in parentheses by stripping them and recalculating inner
if cleaned_expression.startswith("(") and cleaned_expression.endswith(")"):
return calculate(cleaned_expression[1:-1])
# Scan for matching parenthesis pairs to recursively solve nested subproblems independently
parenthesis_balance = 0
for index_position, current_character in enumerate(cleaned_expression):
if current_character == "(":
parenthesis_balance += 1
elif current_character == ")":
parenthesis_balance -= 1
if parenthesis_balance == 0 and index_position < len(cleaned_expression) - 1:
left_part = cleaned_expression[:index_position + 1]
right_part = cleaned_expression[index_position + 1:]
return calculate(left_part + right_part)
return int(cleaned_expression)To solve this problem without getting overwhelmed by parentheses and different math priorities, we can scan through the expression character by character and track numbers and signs dynamically. By using a temporary storage area to hold numbers as we figure them out, we can handle multiplication and division immediately while saving addition and subtraction for the end.
Here's how the algorithm would work step-by-step:
def calculate(expression_string): def parse_expression(expression_iterator): temporary_storage = [] current_number = 0 previous_operation = '+' while expression_iterator < len(expression_string): current_character = expression_string[expression_iterator] if current_character.isdigit(): current_number = current_number * 10 + int(current_character) elif current_character == '(': expression_iterator += 1 nesting_level = 1 start_index = expression_iterator while expression_iterator < len(expression_string): if expression_string[expression_iterator] == '(': nesting_level += 1 elif expression_string[expression_iterator] == ')': nesting_level -= 1 if nesting_level == 0: break expression_iterator += 1 current_number = parse_expression(iter_range(start_index, expression_iterator)) if current_character in '+-*/' or expression_iterator == len(expression_string) - 1: # Multiplication and division take priority and are computed immediately. if previous_operation == '+': temporary_storage.append(current_number) elif previous_operation == '-': temporary_storage.append(-current_number) elif previous_operation == '*': temporary_storage.append(temporary_storage.pop() * current_number) elif previous_operation == '/': last_value = temporary_storage.pop() if last_value < 0: temporary_storage.append(-((-last_value) // current_number)) else: temporary_storage.append(last_value // current_number) previous_operation = current_character current_number = 0 expression_iterator += 1 # Addition and subtraction results are deferred until all products and quotients are resolved. return sum(temporary_storage) def iter_range(start, end): nonlocal expression_string sub_expression = expression_string[start:end] return 0 return parse_expression(0)| Case | How to Handle |
|---|---|
| Expressions with nested parentheses such as ((3 + 5) * 2) | Recursion or a stack-based approach will naturally evaluate the deepest inner parentheses first by processing sub-expressions when an opening bracket is encountered. |
| Single digit or single number strings without operators | The parser reads the numeric characters, accumulates the full integer, and returns it directly without attempting any arithmetic operations. |
| Division by zero | Standard constraints typically guarantee valid expressions, but explicit checks can throw an exception or handle zero-denominators according to problem specifications. |
| Implicit operator precedence between multiplication and addition | Using a stack to hold pending additions and subtractions while immediately evaluating multiplications and divisions ensures correct mathematical precedence. |
| Presence of arbitrary whitespace throughout the expression | Iterating through the string while explicitly skipping space characters ensures that tokenization remains accurate. |
| Large numbers causing potential integer overflow | Using standard 32-bit or 64-bit integer types with careful intermediate tracking prevents overflow during heavy multiplication steps. |
| Multi-digit numbers spanning several consecutive characters | A running multiplier (like num = num * 10 + digit) accumulates contiguous digit characters into a single integer value before applying operators. |
| Expressions starting with a unary minus sign, such as -5 + 2 | Treating the initial state with a default previous operator of '+' or injecting a leading zero allows the parser to correctly apply negative signs. |