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
Mathematical TransformationBad Pair Conditionj - i โ‰  nums[j] - nums[i]Hard to optimize directlyโ†“ Transform โ†“Good Pair Conditionnums[i] - i = nums[j] - jEasy to count with hash map!Example: [4, 1, 3, 3]Transform each element: nums[i] - iโ€ข Index 0: 4 - 0 = 4โ€ข Index 1: 1 - 1 = 0โ€ข Index 2: 3 - 2 = 1โ€ข Index 3: 3 - 3 = 0Frequency count:โ€ข Value 4: appears 1 time โ†’ 0 pairsโ€ข Value 0: appears 2 times โ†’ 1 pairโ€ข Value 1: appears 1 time โ†’ 0 pairsGood pairs: 1Bad pairs: 6 - 1 = 5
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map to store frequency of transformed values, worst case all unique

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109
  • i < j (only count pairs where first index is smaller)
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
42.0K Views
Medium Frequency
~18 min Avg. Time
1.9K 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