Count Equal and Divisible Pairs in an Array

This problem involves counting pairs of elements that both have the same value and whose indices multiply to a multiple of k. We can solve this by first finding pairs of elements with the same value and then checking if the product of their indices is divisible by k.

Here’s the Python code:

1
2
3
4
5
6
7
8
class Solution:
    def countPairs(self, nums: List[int], k: int) -> int:
        count = 0
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] == nums[j] and (i * j) % k == 0:
                    count += 1
        return count

In this solution, we initialize a counter count to zero. We then iterate over the list nums with a nested loop, where the inner loop starts from i+1 to avoid duplicate pairs and pairs with the same index.

For each pair (i, j), we check two conditions:

  1. nums[i] is equal to nums[j] (they have the same value), and
  2. The product of the indices i and j is divisible by k.

If both conditions are met, we increment count. After all pairs have been checked, we return count, which is the number of pairs that meet the given criteria.