KatInterview

Calculate Arithmetic Expression with Negation and Grouping

Stacks & QueuesAuto-graded · 31 test cases
MediumAuto-gradedStacks & Queuesstacksparsingoperator-precedence

Last 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.