Count Number of Bad Pairs (LeetCode 2364): Solution and Explanation

Medium
Array
Hash Table
Math
Counting

A pair (i, j) is good when nums[i] - i equals nums[j] - j. Group indices by that key with a hash map, and every index j adds j minus the size of its bucket to the bad count.

Intuition

Checking every pair is O(n^2), far too slow for 10^5 elements. The trick is to make the condition depend on one index at a time.

The pair is good when j - i == nums[j] - nums[i]. Move the terms around and it becomes nums[i] - i == nums[j] - j. Each index now carries a single key, and good pairs are exactly pairs with the same key.

Counting pairs with equal keys is a classic hash map job. Bad pairs are just all pairs minus good pairs, and you can do that subtraction index by index as you scan.

Approach: Hash map of nums[i] - i

  1. Keep seen, a map from key to how many earlier indices had that key, and a 64-bit counter bad.
  2. For each index j, compute key = nums[j] - j.
  3. Index j forms a pair with each of the j earlier indices. seen[key] of those are good, so add j - seen[key] to bad.
  4. Increment seen[key].
  5. Return bad.

Step-by-step example

nums = [4,1,3,3]
  1. j = 0: key = 4 - 0 = 4. No earlier indices, bad stays 0. seen = {4: 1}.
  2. j = 1: key = 1 - 1 = 0. Neither earlier index has key 0, so both pairs are bad. bad = 1.
  3. j = 2: key = 3 - 2 = 1. Two earlier indices, none with key 1. bad = 3.
  4. j = 3: key = 3 - 3 = 0. Three earlier indices, one (index 1) has key 0. bad += 3 - 1 = 2, so bad = 5.
  5. Return 5.

Code: Python, Java, C++

1class Solution:
2    def countBadPairs(self, nums: List[int]) -> int:
3        seen = {}
4        bad = 0
5        for j, x in enumerate(nums):
6            key = x - j
7            good = seen.get(key, 0)
8            bad += j - good
9            seen[key] = good + 1
10        return bad
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass, with an O(1) average hash map lookup and update per index.

Space

O(n)

The map can hold one entry per index when every key is distinct.

Other approaches

Count good pairs, then subtract (time O(n), space O(n))

Build the full key frequency map first, sum c * (c - 1) / 2 over its counts, and return n * (n - 1) / 2 minus that. Same complexity, two passes.

Sort the keys (time O(n log n), space O(n))

Compute nums[i] - i for every index, sort, and count runs of equal keys. Avoids hashing at the cost of a sort.

Brute force (time O(n^2), space O(1))

Check j - i != nums[j] - nums[i] for every pair. Correct but O(n^2), which times out at n = 10^5.

Common mistakes

  • Using a 32-bit counter. With 10^5 elements there are almost 5 * 10^9 pairs, which overflows an int.
  • Using nums[i] + i as the key. The rearranged condition subtracts the index on both sides.
  • Counting good pairs as seen[key] + 1 or forgetting to update the map after counting, which pairs an index with itself.

Frequently asked questions

Why count good pairs instead of bad ones?

Good pairs have a clean structure: equal keys. Bad pairs are everything else, so it is easier to count the good ones and subtract from the total number of pairs.

Can the key be negative?

Yes, for example nums[5] = 1 gives key -4. A hash map handles negative keys without any special care.

Does the order of the array matter?

Yes. The key ties each value to its position, so shuffling the array changes the keys and the answer.

How is this related to Number of Good Pairs?

It is the same counting idea. Number of Good Pairs groups by the value itself; here you group by value minus index and then take the complement.