Skip to content

Overflow & Underflow in DSA (Complete Notes)


#include <climits>
// int (32-bit)
INT_MIN = -2147483648 // ~ -2e9
INT_MAX = 2147483647 // ~ 2e9
// long long (64-bit)
LLONG_MIN = -9.22e18
LLONG_MAX = 9.22e18

int range = -1e9 to 1e9 ❌

Reality:

int range ≈ -2e9 to 2e9

👉 1e9 is NOT limit → it’s a safe working value


int x = INT_MAX;
x = x + 1; // overflow → garbage value
int x = INT_MIN;
x = x - 1; // underflow → garbage value

return grid[i][j] + min(left, up);

If:

left = INT_MAX

Then:

INT_MAX + grid[i][j] → overflow ❌

dist[u] + wt // overflow if dist[u] = INF

mid = (l + r) / 2; // overflow possible

int x = 1e9;
x * x → overflow ❌

int INF = INT_MAX; // dangerous ❌
int INF = 1e9; // safe ✔
long long INF = 1e18;

Constraint logic:

max path sum ≤ 1e5 or 1e6

So:

1e9 + 1e6 < INT_MAX

👉 No overflow → safe


if (val == INT_MAX) return INT_MAX;
return grid[i][j] + val;

const int INF = 1e9;

long long ans = grid[i][j] + val;

int mid = l + (r - l) / 2;

long long res = 1LL * a * b;

if(out_of_bound) return INT_MAX;
if(out_of_bound) return 1e9;

OR

if(out_of_bound) return -1e9; // for max problems

invalid → return +INF (1e9)
invalid → return -INF (-1e9)

  • Never use INT_MAX in DP transitions

  • Prefer:

int INF = 1e9;
long long INF = 1e18;
  • If values can grow → directly use long long

  • Always think:

"Will I add/multiply this?"

If yes → avoid extreme limits


  • Will I add values? → avoid INT_MAX

  • Will multiplication happen? → use long long

  • DP with invalid states? → use ±1e9

  • Binary search? → safe mid formula


INT_MAX = limit
1e9 = tool

👉 Limits define range
👉 Sentinels define safety

Most DSA bugs are not logic bugs → they are overflow bugs.