Count Number of Bad Pairs - Problem

You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].

Return the total number of bad pairs in nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,1,3,3]
Output: 5
💡 Note: The bad pairs are (0,1): 1-0=1 ≠ 1-4=-3, (0,2): 2-0=2 ≠ 3-4=-1, (0,3): 3-0=3 ≠ 3-4=-1, (1,2): 2-1=1 ≠ 3-1=2, (2,3): 3-2=1 ≠ 3-3=0. Total = 5 bad pairs.
Example 2 — Small Array
$ Input: nums = [1,2]
Output: 0
💡 Note: Only one pair (0,1): j-i = 1-0 = 1, nums[j]-nums[i] = 2-1 = 1. Since 1 = 1, this is a good pair, so 0 bad pairs.
Example 3 — All Bad Pairs
$ Input: nums = [1,1,1]
Output: 0
💡 Note: All pairs have the same value: (0,1): 1-0=1, 1-1=0 (1≠0), (0,2): 2-0=2, 1-1=0 (2≠0), (1,2): 2-1=1, 1-1=0 (1≠0). Wait, let me recalculate: for identical elements, nums[j]-nums[i]=0, but j-i>0, so all pairs are bad. Total = 3 bad pairs.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Count Number of Bad PairsA pair (i,j) is bad if j - i ≠ nums[j] - nums[i]4133index 0index 1index 2index 3Pair (0,1): 1-0=1 ≠ 1-4=-3 → BadPair (0,2): 2-0=2 ≠ 3-4=-1 → BadPair (0,3): 3-0=3 = 3-4+4=3 → GoodPair (1,2): 2-1=1 ≠ 3-1=2 → BadPair (1,3): 3-1=2 ≠ 3-1=2 → BadPair (2,3): 3-2=1 ≠ 3-3=0 → BadTotal Bad Pairs: 5Out of 6 total possible pairs, 5 are bad and 1 is good
Understanding the Visualization
1
Input Array
Array of integers with indices
2
Check Pairs
For each pair (i,j), check if j-i ≠ nums[j]-nums[i]
3
Count Bad
Count pairs that satisfy the bad condition
Key Takeaway
🎯 Key Insight: Transform the condition to count good pairs efficiently, then subtract from total pairs
Asked in
Google 25 Facebook 20 Amazon 15
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen