Sum of two numbers with overflow handling
Filed under Amazon
Free read 1 of 3Identify MAX_INT (2^31 - 1) and MIN_INT (-2^31).
The question
Implement a function to add two integers while handling potential overflow and underflow conditions, returning the result or an error/indicator if it exceeds 32-bit integer limits.
Constraints
- Input integers are within 32-bit range.
- Must handle positive and negative overflow.
- Language-specific limits (e.g., Python handles large ints, so simulate 32-bit behavior).
Examples
- Input
- a=2147483647, b=1
- Output
- OverflowError
- Why
- Sum exceeds max 32-bit signed integer.
Approach
Identify MAX_INT (2^31 - 1) and MIN_INT (-2^31).
If both numbers are positive, check if a > MAX_INT - b. If both are negative, check if a < MIN_INT - b.
Return the sum if safe, otherwise throw an exception or return a specific error code.
Solution
O(1) time, O(1) space
def add(a, b):
MAX, MIN = 2**31 - 1, -2**31
if (b > 0 and a > MAX - b) or (b < 0 and a < MIN - b):
raise OverflowError
return a + b
Tips
- What they are testing: Test with MAX_INT and MIN_INT boundaries.
- Common mistake: Checking for overflow after the addition has already occurred, which might be too late in some languages.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.