Build a validated add-sub calculator
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Given a string `expression`, write a function that validates and evaluates it.
The expression represents arithmetic using only non-negative integers and the operators `+` and `-`.
A valid expression must satisfy all of the following:
- It contains only digits, `+`, and `-`.
- It does not contain spaces, parentheses, or any other characters.
- It consists of numbers separated by binary operators only, so it cannot start or end with an operator.
- Two operators cannot appear next to each other.
- A number cannot have leading zeros unless the number is exactly `0`.
- Every parsed number must fit in the 32-bit signed integer range.
- The final evaluated result must also fit in the 32-bit signed integer range.
If the expression is invalid, report it as invalid. Otherwise, return the computed result.
Examples of invalid inputs include:
- `01+2` because `01` has a leading zero
- `1++2` because two operators are adjacent
- `+1-2` because the expression starts with an operator
- `12a-3` because it contains an invalid character
Examples of valid inputs include:
- `0`
- `12-3+4`
- `7+0-5`
Implement the parser/evaluator and make sure edge cases such as the standalone value `0` are handled correctly.
Quick Answer: This question evaluates skills in string parsing, tokenization, input validation, and safe integer arithmetic handling, with emphasis on enforcing format rules such as operator placement, prevention of leading zeros, and 32-bit signed integer bounds.
Validate and evaluate an expression containing non-negative integers with + and - only.
Constraints
- Inputs are Python literals matching the function signature.
- Return a deterministic exact-match value.
Examples
Input: ('12-3+4',)
Expected Output: {'valid': True, 'value': 13}
Explanation: Valid expression evaluates to 13.
Input: ('01+2',)
Expected Output: {'valid': False, 'value': None}
Explanation: Leading zero is invalid.
Input: ('1++2',)
Expected Output: {'valid': False, 'value': None}
Explanation: Adjacent operators are invalid.
Input: ('2147483648',)
Expected Output: {'valid': False, 'value': None}
Explanation: Number overflow is invalid.
Hints
- Clarify edge cases before coding.
- Keep the return value deterministic.