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: 3
💡 Note: All pairs have different values for j-i vs nums[j]-nums[i]: (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). Total = 3 bad pairs.

Constraints

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

Visualization

Tap to expand
Count Number of Bad Pairs INPUT nums = [4, 1, 3, 3] 4 i=0 1 i=1 3 i=2 3 i=3 Bad Pair Definition: i < j AND j - i != nums[j] - nums[i] All Pairs (6 total): (0,1) (0,2) (0,3) (1,2) (1,3) (2,3) nums[i] - i values: [4, 0, 1, 0] (4-0, 1-1, 3-2, 3-3) ALGORITHM STEPS 1 Rearrange equation j-i = nums[j]-nums[i] nums[i]-i = nums[j]-j 2 Use HashMap Track count of nums[i]-i HashMap Progress: i=0: diff=4, map={4:1} i=1: diff=0, map={4:1,0:1} i=2: diff=1, map={4:1,0:1,1:1} i=3: diff=0, map={4:1,0:2,1:1} 3 Count Good Pairs Same diff = good pair Good: (1,3) has diff=0 4 Calculate Result Bad = Total - Good Bad = 6 - 1 = 5 Total pairs = n*(n-1)/2 = 6 FINAL RESULT Bad Pairs Found: X (0,1): 1-0=1, 1-4=-3 X (0,2): 2-0=2, 3-4=-1 X (0,3): 3-0=3, 3-4=-1 X (1,2): 2-1=1, 3-1=2 X (1,3): 3-1=2, 3-1=2 OK (1,3) is GOOD Good Pairs: 1 (1,3): both have diff=0 OUTPUT 5 5 bad pairs found Key Insight: Transform the problem: j - i = nums[j] - nums[i] becomes nums[i] - i = nums[j] - j Good pairs have the same (nums[i] - i) value. Use HashMap to count occurrences in O(n) time. Bad pairs = Total pairs - Good pairs = n*(n-1)/2 - sum of C(count,2) for each diff value. TutorialsPoint - Count Number of Bad Pairs | Optimal Solution O(n)
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