Evaluate an Arithmetic Expression
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in parsing arithmetic expressions, handling unary and binary operators, parentheses, whitespace, numeric tokenization, and robust syntactic validation.
Part 1: Evaluate a Simplified Arithmetic Expression
Constraints
- 1 <= len(s) <= 100000
- s contains only digits, spaces, '+', '-', '(' and ')'
- The expression is guaranteed to be syntactically valid
- The final answer fits in a signed 64-bit integer
Examples
Input: ("0",)
Expected Output: 0
Explanation: A single number evaluates to itself.
Input: (" 2-1 + 2 ",)
Expected Output: 3
Explanation: Ignoring spaces, 2 - 1 + 2 = 3.
Input: ("(1+(4+5+2)-3)+(6+8)",)
Expected Output: 23
Explanation: The left group is 1 + 11 - 3 = 9, and the right group is 14, so the total is 23.
Input: ("-(-42)",)
Expected Output: 42
Explanation: The inner value is -42, and negating it gives 42.
Input: ("-(3-(2-1))",)
Expected Output: -2
Explanation: First compute (2 - 1) = 1, then 3 - 1 = 2, and finally apply the outer unary minus.
Input: ("( -7 )",)
Expected Output: -7
Explanation: The unary minus appears immediately after '(', so the value inside the parentheses is -7.
Input: ("+(1-(+2-3)+(4-(5-6)))",)
Expected Output: 7
Explanation: Compute (+2 - 3) = -1 and (5 - 6) = -1, so the full expression becomes 1 - (-1) + (4 - (-1)) = 2 + 5 = 7.
Hints
- Keep a running result and a current sign for the number you are building.
- When you enter parentheses, save the outer result and sign on a stack so you can restore them after evaluating the inner expression.
Part 2: Validate and Evaluate an Arithmetic Expression
Constraints
- 0 <= len(s) <= 100000
- s may contain arbitrary characters, but only digits, spaces, '+', '-', '(' and ')' can appear in a valid expression
- Unary '+' and '-' are allowed only at the start of the whole expression or immediately after '('
- If the expression is valid, the final answer fits in a signed 64-bit integer
Examples
Input: (1 + (4 - 2)) - 3
Expected Output:
Explanation: This expression is valid and evaluates to 0.
Input: -(3 - 1) + 5
Expected Output:
Explanation: A unary minus at the start may apply to a parenthesized group.
Input: 1 +- 2
Expected Output: ERROR
Explanation: After a binary '+', another operator is not allowed here.
Input: (2 + 3
Expected Output: ERROR
Explanation: The opening parenthesis is never closed.
Input:
Expected Output: ERROR
Explanation: Edge case: an empty expression containing only spaces is invalid.
Hints
- Track what kind of token is expected next: an operand, or an operator/closing parenthesis.
- You can validate and evaluate in one pass by combining a stack for parentheses with a small state machine.