Count Equal and Divisible Pairs in an Array (LeetCode 2176): Solution and Explanation

Easy
Array

Given an integer array nums and an integer k, count the index pairs (i, j) with i < j, nums[i] == nums[j], and i * j divisible by k.

Intuition

The pair has two conditions, and one of them is much cheaper to filter on. Two indices can only qualify if their values match, so most pairs can be thrown away without ever computing a product.

Grouping indices by value does that filtering for free. As the scan reaches index j, the candidates are exactly the earlier indices stored under nums[j].

For each candidate i, the second condition is a single modulo test on i * j. Since n is at most 100, testing every candidate inside the group is fast, and it skips all the pairs with different values.

Approach: Group indices by value, test inside the group

  1. Create an empty map groups from value to the list of indices where it appeared, and set pairs = 0.
  2. For each index j with value x, loop over the earlier indices i in groups[x].
  3. If (i * j) % k == 0, increment pairs.
  4. Append j to groups[x] so later copies of x test against it, then continue the scan.
  5. Return pairs.

Step-by-step example

nums = [3,1,2,2,2,1,3], k = 2
  1. Indices 0, 1 and 2 are the first copies of 3, 1 and 2, so there is nothing to test yet.
  2. j = 3 (value 2) tests i = 2: 2 * 3 = 6 is divisible by 2, so pairs = 1.
  3. j = 4 (value 2) tests i = 2: 8 is divisible, pairs = 2. Then i = 3: 12 is divisible, pairs = 3.
  4. j = 5 (value 1) tests i = 1: 1 * 5 = 5 leaves remainder 1, so it does not count.
  5. j = 6 (value 3) tests i = 0: 0 * 6 = 0 is divisible, pairs = 4. The answer is 4.

Code: Python, Java, C++

1class Solution:
2    def countPairs(self, nums: List[int], k: int) -> int:
3        groups = {}
4        pairs = 0
5        for j, x in enumerate(nums):
6            for i in groups.get(x, []):
7                if i * j % k == 0:
8                    pairs += 1
9            groups.setdefault(x, []).append(j)
10        return pairs
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

In the worst case every value is equal and every pair is tested. Usually the groups are small and far fewer pairs are checked.

Space

O(n)

The groups together store each index once.

Other approaches

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

Two nested loops check both conditions for every i < j. Same worst case, slightly more work on inputs with many distinct values.

Count by gcd with k (time O(n * d(k)) roughly, d(k) = number of divisors of k, space O(n))

i * j is divisible by k exactly when gcd(i, k) * gcd(j, k) is. Within each value group, count indices by gcd(index, k) and combine the divisor classes. This scales to much larger n but is overkill here.

Common mistakes

  • Forgetting that index 0 qualifies with every later equal value, since 0 * j = 0 is divisible by any k.
  • Testing the values instead of the indices for divisibility. The product uses positions i and j, not nums[i] and nums[j].
  • Counting (i, j) and (j, i) separately. Only pairs with i < j count, which testing against earlier indices handles.
  • Using 1-based indices. The problem is 0-indexed, and switching to 1-based changes which products are divisible.

Frequently asked questions

Why is O(n^2) acceptable here?

n is at most 100, so there are at most 4,950 pairs. Even the slowest approach finishes instantly.

Does grouping by value change the worst case?

No. If all values are equal the single group holds every index and every pair is tested. Grouping helps when values are spread out.

How does the gcd trick work?

k divides i * j exactly when (k / gcd(i, k)) divides j. So you can bucket earlier indices by gcd(i, k) and, for each j, add the buckets whose gcd values make the product a multiple of k.