Count Equal and Divisible Pairs in an Array
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.
Examples
Example 1:
Input: nums = [3,1,2,2,2,1,3], k = 2
Output: 4
Explanation:
There are 4 pairs that meet all the requirements:
- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.
- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.
- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.
- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.
Example 2:
Input: nums = [1,2,3,4], k = 1
Output: 0
Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.
Constraints:
1 <= nums.length <= 1001 <= nums[i], k <= 100
Solution
Method 1 - Iterate on pairs
To solve this problem, we need to iterate through the array to find pairs (i, j) such that:
nums[i] == nums[j](the elements at indicesiandjare equal).(i * j)is divisible byk.
The approach involves:
- Using nested loops to examine all
(i, j)pairs (i < j). - For each pair, checking the two conditions (
nums[i] == nums[j]and(i * j % k == 0)). - If both conditions are satisfied, increment a counter to record the pair.
Approach
- Initialisation: Start with
ans = 0to store the count of valid pairs. - Iterate through array:
- Use nested loops to check all pairs
(i, j)such thati < j.
- Use nested loops to check all pairs
- Evaluate conditions:
nums[i] == nums[j]: Check if the elements are equal.(i * j) % k == 0: Check if the product of the indices is divisible byk.
- Update result: Increment
ansfor every pair that meets both conditions. - Return result: Return
ansafter checking all pairs.
Code
Java
class Solution {
public int countPairs(int[] nums, int k) {
int ans = 0;
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] == nums[j] && (i * j) % k == 0) {
ans++;
}
}
}
return ans;
}
}
Python
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
ans: int = 0
n: int = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] == nums[j] and (i * j) % k == 0:
ans += 1
return ans
Complexity
- ⏰ Time complexity:
O(n^2). The solution involves a nested loop to compare all pairs, hence the time complexity isO(n^2)wherenis the length of the input array. - 🧺 Space complexity:
O(1). The space complexity isO(1)as no additional data structures are used (other than variables for computations).