Count Number of Bad Pairs - Problem
Given a 0-indexed integer array nums, you need to count pairs of indices that don't maintain a consistent relationship.
A pair of indices (i, j) where i < j is considered a "bad pair" if the difference between their indices doesn't equal the difference between their values. In mathematical terms: j - i โ nums[j] - nums[i].
Goal: Return the total count of bad pairs in the array.
Example: In array [4, 1, 3, 3], the pair (0, 1) is bad because 1 - 0 = 1 but nums[1] - nums[0] = 1 - 4 = -3, and 1 โ -3.
Input & Output
example_1.py โ Python
$
Input:
nums = [4,1,3,3]
โบ
Output:
5
๐ก Note:
Check all pairs: (0,1): 1-0=1, 1-4=-3, 1โ -3 โ | (0,2): 2-0=2, 3-4=-1, 2โ -1 โ | (0,3): 3-0=3, 3-4=-1, 3โ -1 โ | (1,2): 2-1=1, 3-1=2, 1โ 2 โ | (1,3): 3-1=2, 3-1=2, 2=2 โ | (2,3): 3-2=1, 3-3=0, 1โ 0 โ. Total bad pairs: 5
example_2.py โ Python
$
Input:
nums = [1,2,3,4,5]
โบ
Output:
0
๐ก Note:
This is an arithmetic sequence with difference 1. For any pair (i,j): j-i equals nums[j]-nums[i] because both equal j-i. All pairs are good, so bad pairs = 0.
example_3.py โ Python
$
Input:
nums = [1]
โบ
Output:
0
๐ก Note:
Array has only one element. No pairs possible, so bad pairs = 0.
Visualization
Tap to expand
Understanding the Visualization
1
Original Problem
Count pairs where j - i โ nums[j] - nums[i]
2
Transform Equation
Rewrite as: good pairs satisfy nums[i] - i = nums[j] - j
3
Count Good Pairs
Use hash map to count frequencies and calculate combinations
4
Get Answer
Bad pairs = Total pairs - Good pairs
Key Takeaway
๐ฏ Key Insight: Transform the inequality to find good pairs easily, then subtract from total pairs!
Time & Space Complexity
Time Complexity
O(n)
Single pass through array to build frequency map and calculate result
โ Linear Growth
Space Complexity
O(n)
Hash map to store frequency of transformed values, worst case all unique
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- i < j (only count pairs where first index is smaller)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code