Before attempting this problem, you should be comfortable with:
A bad pair is defined as i < j where j - i != nums[j] - nums[i]. We can check every possible pair of indices and count how many satisfy this condition.
i, the inner loop picks index j where j > i.j - i != nums[j] - nums[i].Rearranging the bad pair condition j - i != nums[j] - nums[i] gives us nums[j] - j != nums[i] - i. This means a pair is "good" when both elements have the same value of nums[k] - k. Instead of counting bad pairs directly, we count the total pairs and subtract the good pairs. Elements with the same transformed value form good pairs among themselves.
nums[i] - i value.i at index i).Trying to count bad pairs directly with a hash map is error-prone. The cleaner approach is to count good pairs (where nums[i] - i == nums[j] - j) and subtract from total pairs.
With n up to 10^5, the total number of pairs is n*(n-1)/2 which can exceed 32-bit integer limits. Use long or 64-bit integers for the result.
// Wrong: overflow for large n
int res = 0;
// Correct: use long
long res = 0;The key insight is rewriting j - i != nums[j] - nums[i] as nums[i] - i != nums[j] - j. Without this transformation, you cannot efficiently group elements using a hash map.