#2176

Count Equal and Divisible Pairs in an Array

Easy
ArrayHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a hashmap to count occurrences of each number and their indices. This allows us to efficiently check pairs without needing to iterate through all combinations, significantly reducing the time complexity.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a hashmap to store lists of indices for each unique number in nums.
  2. 2Step 2: Populate the hashmap with indices for each number in nums.
  3. 3Step 3: For each unique number, retrieve its list of indices and check all pairs of indices (i, j) where i < j.
  4. 4Step 4: For each pair, check if (i * j) is divisible by k and increment the count if true.
  5. 5Step 5: Return the final count.
solution.py21 lines
1# Full working Python code
2
3def countPairs(nums, k):
4    from collections import defaultdict
5    index_map = defaultdict(list)
6    count = 0
7    n = len(nums)
8
9    for i in range(n):
10        index_map[nums[i]].append(i)
11
12    for indices in index_map.values():
13        m = len(indices)
14        for i in range(m):
15            for j in range(i + 1, m):
16                if (indices[i] * indices[j]) % k == 0:
17                    count += 1
18    return count
19
20# Example usage
21print(countPairs([3,1,2,2,2,1,3], 2))  # Output: 4

Complexity note: The time complexity is O(n) because we traverse the array once to build the hashmap and then process each unique number's indices. The space complexity is O(n) due to the hashmap storing indices for each unique number.

  • 1Using a hashmap allows us to efficiently group indices by value, reducing the number of comparisons needed.
  • 2Divisibility checks can be performed directly on the indices, avoiding unnecessary calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.