Count Number of Bad Pairs

Solve this Problem
Medium20–25 min
Topics
Companies
Practice:LeetCode ↗GFG ↗
A pair of indices (i, j) with i < j is called bad when the gap between the indices doesn't match the gap between the values at those indices — that is, j - i ≠ nums[j] - nums[i]. Count how many bad pairs exist among all pairs of indices in the array.

Test Case 1:

Input:nums = [2, 3, 4, 7, 10]
Output:7
Explanation:Indices 0, 1, 2 all share nums[k] - k = 2, so those 3 pairs are good; the other 7 pairs are bad.

Test Case 2:

Input:nums = [5, 5, 5, 5]
Output:6
Explanation:Every nums[k] - k is distinct, so every one of the 6 pairs is bad.

Test Case 3:

Input:nums = [1, 2]
Output:0
Explanation:The only pair is good (gap 1 matches value gap 1), so there are no bad pairs.

Constraints

  • 1 ≤ nums.length ≤ 10
  • -100 ≤ nums[i] ≤ 100
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

Approach & Solutions

Brute Force — Check Every Pair Directly

Good

A pair of indices (i, j) with i < j is bad when the gap between the indices doesn't match the gap between the values there — that is, j - i ≠ nums[j] - nums[i]. Check every pair directly against that condition and count how many fail it. Simple and correct, but checking all C(n, 2) pairs one at a time means the work grows with the square of the array size.

TimeO(n²)
SpaceO(1)
1class Solution { 2 public int countBadPairs(int[] nums) { 3 int n = nums.length; 4 int count = 0; 5 for (int i = 0; i < n; i++) { 6 for (int j = i + 1; j < n; j++) { 7 if ((j - i) != (nums[j] - nums[i])) { 8 count++; 9 } 10 } 11 } 12 return count; 13 } 14}

Optimal — Total Minus Good Pairs via HashMap

Optimal

Rearranging j - i ≠ nums[j] - nums[i] gives nums[j] - j ≠ nums[i] - i — a pair is GOOD exactly when nums[k] - k is the same for both indices. So instead of testing every pair, count how many indices share each value of nums[k] - k with a hash map; any group of c indices sharing a value contributes C(c, 2) good pairs. Sum those up across every group to get the total good-pair count, then subtract it from C(n, 2) (every possible pair) to get the number of bad pairs — all in a single pass plus one pass over the map.

TimeO(n)
SpaceO(n)
1class Solution { 2 public int countBadPairs(int[] nums) { 3 int n = nums.length; 4 int total = n * (n - 1) / 2; 5 Map<Integer, Integer> diffCount = new HashMap<>(); 6 for (int k = 0; k < n; k++) { 7 int d = nums[k] - k; 8 diffCount.merge(d, 1, Integer::sum); 9 } 10 int good = 0; 11 for (int c : diffCount.values()) { 12 good += c * (c - 1) / 2; 13 } 14 return total - good; 15 } 16}

Related Problems