Magicsheet logo

Count Number of Bad Pairs

Medium
25%
Updated 8/1/2025

Count Number of Bad Pairs

What is this problem about?

In an array nums, a pair of indices (i,j)(i, j) is called a "bad pair" if i<ji < j and jieqnums[j]nums[i]j - i eq nums[j] - nums[i]. You need to find the total number of bad pairs in the array. This problem is about calculating the complement: it's often easier to count "good pairs" and subtract them from the total number of possible pairs.

Why is this asked in interviews?

Companies like Microsoft and Google use this problem to see if a candidate can recognize mathematical patterns and optimize a quadratic brute-force approach. The condition for a "good pair" is ji==nums[j]nums[i]j - i == nums[j] - nums[i], which can be rearranged to nums[i]i==nums[j]jnums[i] - i == nums[j] - j. This simple algebraic shift allows the problem to be solved using a frequency map in linear time.

Algorithmic pattern used

The pattern used is Mathematical Rearrangement and Complementary Counting with a Hash Table.

  1. Total pairs in an array of size nn is (n2)=nimes(n1)2\binom{n}{2} = \frac{n imes (n-1)}{2}.
  2. A pair is "good" if nums[i]i==nums[j]jnums[i] - i == nums[j] - j.
  3. Use a Hash Map to count how many times each value of (nums[i]i)(nums[i] - i) appears.
  4. Total bad pairs = Total pairs - Good pairs.

Example explanation

Array: [4, 1, 3, 3]

  • Index 0: 40=44 - 0 = 4
  • Index 1: 11=01 - 1 = 0
  • Index 2: 32=13 - 2 = 1
  • Index 3: 33=03 - 3 = 0
  • Transformed values: [4, 0, 1, 0].
  • Map: {4: 1, 0: 2, 1: 1}.
  • Good pairs: Only the two 0s can form a pair. (22)=1\binom{2}{2} = 1.
  • Total pairs: (42)=6\binom{4}{2} = 6.
  • Bad pairs: 61=56 - 1 = 5.

Common mistakes candidates make

The most common mistake is attempting to check all pairs using a nested loop, which is O(n2)O(n^2) and will time out for large arrays. Another mistake is forgetting to use 64-bit integers (long) for the counts, as the number of pairs can grow very large (101010^{10} for n=105n=10^5).

Interview preparation tip

Always look for the "total minus something" strategy when counting "bad" or "invalid" items. If the condition for being "bad" is complex, check if the condition for being "good" is simpler to calculate using a Hash Map.

Similar Questions