VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-for-integer-overflow/

⇱ Check for Integer Overflow - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check for Integer Overflow

Last Updated : 26 Mar, 2025

Given two integers a and b. The task is to design a function that adds two integers and detects overflow during the addition. If the sum does not cause an overflow, return their sum. Otherwise, return -1 to indicate an overflow.
Note: You cannot use type casting to a larger data type to check for overflow. Also, the function must handle both positive and negative integers correctly.

Examples:

Input: a = 1000000000, b = 1000000000
Output: 2000000000
Explanation: The sum 1000000000 + 1000000000 = 2000000000 is within the valid integer range, so no overflow occurs, and the function stores the result successfully.

Input: a = -2000000000, b = -500000000
Output: -1
Explanation: The sum -2000000000 + (-5000000000) = -7000000000 exceeds the maximum limit of an integer (assuming 32 bit representation), causing an overflow.

Input: a = -100, b = 100
Output: 0
Explanation: The sum -100 + 100 = 0 is within the valid integer range, so no overflow occurs, and the function stores the result successfully.

[Expected Approach] Observation on Signs of the Integers - O(1) Time and O(1) Space

The idea is to detect overflow by observing how the sum behaves relative to the input values. The thought process is that overflow can only occur if both numbers have the same sign, but the sum has the opposite sign. The key observation is that in a typical integer representation, exceeding the maximum or minimum limit causes a wraparound effect, flipping the sign unexpectedly. By checking if this sign reversal happens, we can accurately determine overflow and return an error indicator.

  • Calculate sum
  • If both numbers are positive and sum is negative then return -1
  • OR If both numbers are negative and sum is positive then return -1
  • Else return sum.

Output
2000000000

Time Complexity: O(1), due to constant number of operations (addition and comparisons).
Space Complexity: O(1), as only a few integer variables are used.

[Alternate Approach] Checking the Sum - O(1) Time and O(1) Space

The idea remains the same as in the previous approach, checking for integer overflow while performing addition. Instead of relying on post-addition checks, we now prevent overflow before it happens by ensuring that the sum does not exceed Max Integer Value for positive numbers or go below Min Integer Value for negative numbers.


Output
2000000000

Time Complexity: O(1), due to constant number of operations (addition and comparisons).
Space Complexity: O(1), as only a few integer variables are used. 

Comment
Article Tags: