Count Equal and Divisible Pairs in an Array - Problem
You are given a 0-indexed integer array nums of length n and an integer k. Your task is to find all special pairs in the array.
A pair (i, j) is considered special if it satisfies both of these conditions:
0 โค i < j < n(valid pair indices with i before j)nums[i] == nums[j](elements at these positions are equal)(i * j)is divisible byk(product of indices is divisible by k)
Goal: Return the count of all such special pairs.
Example: If nums = [3,1,2,2,2,1,3] and k = 2, we need to find pairs where elements are equal AND the product of their indices is divisible by 2.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [3,1,2,2,2,1,3], k = 2
โบ
Output:
4
๐ก Note:
Valid pairs: (0,6) since nums[0]==nums[6]=3 and (0*6)%2=0, (2,3) since nums[2]==nums[3]=2 and (2*3)%2=0, (2,4) since nums[2]==nums[4]=2 and (2*4)%2=0, (3,4) since nums[3]==nums[4]=2 and (3*4)%2=0
example_2.py โ All Equal Elements
$
Input:
nums = [1,2,3,4], k = 1
โบ
Output:
0
๐ก Note:
No pairs have equal elements, so the count is 0. The divisibility condition doesn't matter if elements aren't equal.
example_3.py โ Edge Case Small Array
$
Input:
nums = [1,1], k = 3
โบ
Output:
0
๐ก Note:
Only one pair (0,1) with nums[0]==nums[1]=1, but (0*1)%3=0, so this should count as 1. Wait, actually 0%3=0, so the answer should be 1.
Visualization
Tap to expand
Understanding the Visualization
1
Find Equal Elements
Identify pairs of elements with the same value (matching outfits)
2
Check Index Product
For equal pairs, verify if the product of their indices is divisible by k
3
Count Valid Pairs
Sum up all pairs that satisfy both conditions
4
Return Result
Return the total count of special pairs found
Key Takeaway
๐ฏ Key Insight: We must check both equality and divisibility conditions for each pair, making the brute force O(nยฒ) approach unavoidable but acceptable given the constraints.
Time & Space Complexity
Time Complexity
O(nยฒ)
Worst case when all elements are equal, we still check all pairs. Best case O(n) when all elements are unique.
โ Quadratic Growth
Space Complexity
O(n)
Hash map stores up to n indices across all value groups
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 100
- 1 โค nums[i], k โค 100
- Note: The constraint on array length makes brute force acceptable
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code