Chapter 141

Home

Common Bug Patterns

Most WA submissions fall into a small set of bug patterns. Recognising them saves hours of debugging.

Top 5 Contest Bugs

1. Off-by-one in binary search / loop bounds

while (lo < hi) vs while (lo <= hi). Test with N=1, N=2.

2. Integer overflow

int for N = 2×10⁵, values up to 10⁹. Sum needs long long. mid = (lo+hi)/2 overflows for 10⁹+10⁹.

3. Uninitialised / undefined behaviour

Reading uninitialised int in C++ is UB. Always initialise or use vector<int> v(n, 0).

4. Incorrect modulo handling

Negative values after subtraction: (a - b + MOD) % MOD. Forgot to mod after multiplication.

5. Not resetting data structures between test cases

Global arrays, visited flags, segment trees — if the problem has T test cases, clear everything.