Count Equal and Divisible Pairs in an Array

easy array hash map

Problem

Given an array nums and an integer k, return the number of index pairs (i, j) with i < j such that nums[i] = nums[j] and (i · j) is divisible by k.

Inputnums = [3,1,2,2,2,1,3], k = 2
Output4
Equal pairs with i·j a multiple of 2.

def count_pairs(nums, k):
    seen = {}
    count = 0
    for j, v in enumerate(nums):
        for i in seen.get(v, []):
            if (i * j) % k == 0:
                count += 1
        seen.setdefault(v, []).append(j)
    return count
function countPairs(nums, k) {
  const seen = new Map();
  let count = 0;
  for (let j = 0; j < nums.length; j++) {
    const list = seen.get(nums[j]) || [];
    for (const i of list) if ((i * j) % k === 0) count++;
    list.push(j);
    seen.set(nums[j], list);
  }
  return count;
}
class Solution {
    public int countPairs(int[] nums, int k) {
        Map<Integer, List<Integer>> seen = new HashMap<>();
        int count = 0;
        for (int j = 0; j < nums.length; j++) {
            List<Integer> list = seen.computeIfAbsent(nums[j], x -> new ArrayList<>());
            for (int i : list) if ((i * j) % k == 0) count++;
            list.add(j);
        }
        return count;
    }
}
int countPairs(vector<int>& nums, int k) {
    unordered_map<int, vector<int>> seen;
    int count = 0;
    for (int j = 0; j < (int)nums.size(); j++) {
        for (int i : seen[nums[j]]) if ((i * j) % k == 0) count++;
        seen[nums[j]].push_back(j);
    }
    return count;
}
Time: O(n²) worst case Space: O(n)