Calculate Arithmetic Expression with Negation and Grouping
Stacks & QueuesAuto-graded · 31 test casesLast updated
Tests building an operator-precedence parser using stacks to handle binary operations, unary negation, parentheses, and zero-truncating division.
Write a function that calculates the integer value of an arithmetic expression provided as a string.
The expression consists of:
- Non-negative integer literals (sequences of digits)
- Binary operators:
+,-,*,/ - Parentheses:
(and) - Whitespace characters (spaces)
Operator Precedence and Associativity:
- Multiplication
*and division/have higher precedence than addition+and subtraction- - Operators with the same precedence level evaluate from left to right
- Parentheses override the default precedence
Unary Negation:
- A minus sign
-acts as a unary negation operator (not binary subtraction) when it appears:- At the very start of the expression (ignoring leading spaces)
- Immediately after an opening parenthesis
((ignoring spaces between the(and the-)
- When used as negation, the minus applies to the immediately following number or parenthesized subexpression
- The plus sign
+is never unary; it always represents binary addition
Division Rules:
- Division
/performs integer division that truncates toward zero - Examples:
7 / 2 = 3,-7 / 2 = -3,7 / -2 = -3,-7 / -2 = 3 - This differs from Python's
//operator, which floors toward negative infinity
Implementation Requirement:
- Do not use built-in expression evaluation functions such as
eval()
Constraints
1 <= len(expression) <= 10^4- The expression contains only: digits
0-9, operators+,-,*,/, parentheses(,), and space characters - The expression is guaranteed to be syntactically valid
- No division by zero occurs
- All integer literals, intermediate results, and the final result fit within
[-2^31, 2^31 - 1] - Parentheses may be nested to depths approaching half the expression length
- Spaces may appear anywhere between tokens but never within a multi-digit number
Examples
Example 1
Input: compute_expression('2 + 3 * (4 - 1) / 2')
Output: 6
Example 2
Input: compute_expression('-(3 + 4) / 2')
Output: -3
Example 3
Input: compute_expression('14 - 3 - (2 - (-5))')
Output: 4
Hints
Hint 1
Maintain two stacks: one for numeric values and another for operators. Scan the string from left to right.
Hint 2
Keep track of whether the next token should be an operand. This context tells you whether a minus sign represents negation or subtraction.
Hint 3
When encountering a new operator, first process all operators already on the stack that have greater than or equal precedence. This maintains correct precedence and left-associativity.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires implementing an expression evaluator that respects operator precedence, handles left-to-right associativity, supports parentheses, and distinguishes unary negation from binary subtraction. The solution employs a two-stack algorithm that processes the expression in a single left-to-right pass.
Two Stack Structure:
- A numbers stack holding operand values
- An operators stack holding pending operators and parenthesis markers
Core Logic:
When scanning left to right, each token is handled based on its type:
- Whitespace: Skip and advance to the next character
- Digit: Read the complete multi-digit number, push it onto the numbers stack, and mark that we're no longer expecting an operand
- Opening parenthesis
(: Push it as a marker onto the operators stack and mark that the next token should be an operand - Closing parenthesis
): Evaluate all operators back to the matching opening parenthesis, pop the marker, and mark that we're not expecting an operand - Minus sign when expecting an operand: Push it as a unary negation operator with highest precedence
- Binary operator: Before pushing the new operator, evaluate all operators on the stack that have equal or higher precedence (but stop at parenthesis markers). Then push the new operator and mark that an operand is expected next
The expecting_operand Flag:
A boolean flag tracks whether the parser is currently positioned where an operand (number or opening parenthesis) should appear. This flag is true:
- At the beginning of the expression
- Right after an opening parenthesis
- Right after any binary operator
This context-sensitive approach correctly distinguishes - 5 (negation) from 5 - 3 (subtraction) even when spaces appear in various positions.
Handling Division:
Python's floor division // rounds toward negative infinity, giving -7 // 2 = -4. The problem requires truncation toward zero, giving -7 / 2 = -3. We achieve this by computing abs(left) // abs(right) and then applying the sign based on whether the two operands have matching signs.
Final Reduction:
After scanning all tokens, any operators remaining on the stack are evaluated in order. The single value left on the numbers stack is the result.
Why This Works
Precedence: The comparison precedence[operators[-1]] >= current_prec ensures that higher-precedence operators are evaluated before lower-precedence ones. In 2 + 3 * 4, when the * arrives, nothing is reduced because + has lower precedence. When the end of input arrives, * is evaluated first, then +.
Left Associativity: The >= comparison (not just >) ensures that when operators have equal precedence, the leftmost one is evaluated first. In 10 - 5 - 2, when the second - arrives, the first - has equal precedence and is immediately reduced, producing (10 - 5) - 2 = 3 rather than 10 - (5 - 2) = 7.
Parentheses as Barriers: The opening parenthesis marker stops reductions from crossing scope boundaries. When a closing parenthesis is encountered, operators are reduced only up to the matching opening parenthesis, treating the entire parenthesized group as a single value.
Iterative Design: Using explicit stacks rather than recursion allows the solution to handle deeply nested parentheses without hitting recursion depth limits, which would fail around 1000 levels in Python.
Complexity
- Time: O(n), where n is the length of the expression. Each character is examined once. Each number and operator is pushed onto a stack exactly once and popped exactly once.
- Space: O(n) in the worst case. Deeply nested parentheses can fill the operators stack with many markers and pending operators.
Solution
def compute_expression(expression: str) -> int:
def apply_operator(numbers, operator):
if operator == 'negate':
numbers.append(-numbers.pop())
return
right = numbers.pop()
left = numbers.pop()
if operator == '+':
numbers.append(left + right)
elif operator == '-':
numbers.append(left - right)
elif operator == '*':
numbers.append(left * right)
else: # operator == '/'
quotient = abs(left) // abs(right)
numbers.append(quotient if (left < 0) == (right < 0) else -quotient)
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, 'negate': 3}
numbers = []
operators = []
idx = 0
length = len(expression)
expecting_operand = True
while idx < length:
char = expression[idx]
if char == ' ':
idx += 1
continue
if char.isdigit():
start = idx
while idx < length and expression[idx].isdigit():
idx += 1
numbers.append(int(expression[start:idx]))
expecting_operand = False
continue
if char == '(':
operators.append('(')
expecting_operand = True
elif char == ')':
while operators[-1] != '(':
apply_operator(numbers, operators.pop())
operators.pop()
expecting_operand = False
elif char == '-' and expecting_operand:
operators.append('negate')
else:
current_prec = precedence[char]
while operators and operators[-1] != '(' and precedence[operators[-1]] >= current_prec:
apply_operator(numbers, operators.pop())
operators.append(char)
expecting_operand = True
idx += 1
while operators:
apply_operator(numbers, operators.pop())
return numbers[0]