Count Equal and Divisible Pairs in an Array (LeetCode 2176): Solution and Explanation
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
- Create an empty map
groupsfrom value to the list of indices where it appeared, and setpairs = 0. - For each index
jwith valuex, loop over the earlier indicesiingroups[x]. - If
(i * j) % k == 0, incrementpairs. - Append
jtogroups[x]so later copies ofxtest against it, then continue the scan. - Return
pairs.
Step-by-step example
nums = [3,1,2,2,2,1,3], k = 2
- Indices 0, 1 and 2 are the first copies of 3, 1 and 2, so there is nothing to test yet.
- j = 3 (value 2) tests i = 2: 2 * 3 = 6 is divisible by 2, so pairs = 1.
- j = 4 (value 2) tests i = 2: 8 is divisible, pairs = 2. Then i = 3: 12 is divisible, pairs = 3.
- j = 5 (value 1) tests i = 1: 1 * 5 = 5 leaves remainder 1, so it does not count.
- 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 pairs1class Solution {
2 public int countPairs(int[] nums, int k) {
3 Map<Integer, List<Integer>> groups = new HashMap<>();
4 int pairs = 0;
5 for (int j = 0; j < nums.length; j++) {
6 List<Integer> seen = groups.computeIfAbsent(nums[j], key -> new ArrayList<>());
7 for (int i : seen) {
8 if (i * j % k == 0) {
9 pairs++;
10 }
11 }
12 seen.add(j);
13 }
14 return pairs;
15 }
16}1class Solution {
2public:
3 int countPairs(vector<int>& nums, int k) {
4 unordered_map<int, vector<int>> groups;
5 int pairs = 0;
6 for (int j = 0; j < (int)nums.size(); j++) {
7 vector<int>& seen = groups[nums[j]];
8 for (int i : seen) {
9 if (i * j % k == 0) {
10 pairs++;
11 }
12 }
13 seen.push_back(j);
14 }
15 return pairs;
16 }
17};Time and space complexity
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.
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.