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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code