Count Equal and Divisible Pairs in an Array - 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] (elements are equal)
  • (i * j) is divisible by k

A pair (i, j) satisfies the conditions if both the values at indices i and j are the same, and the product of their indices is divisible by k.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1,2,2,2,1,3], k = 2
Output: 4
💡 Note: Valid pairs: (2,3), (2,4), (3,4), (0,6). All have equal values and index products divisible by 2.
Example 2 — No Valid Pairs
$ Input: nums = [1,2,3,4], k = 1
Output: 0
💡 Note: No two elements are equal, so no valid pairs exist regardless of divisibility.
Example 3 — All Same Values
$ Input: nums = [5,5,5,5], k = 3
Output: 5
💡 Note: Equal value pairs: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). Pairs (0,1), (0,2), (0,3), (1,3), (2,3) have index products 0, 0, 0, 3, 6 respectively, all divisible by 3.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i], k ≤ 100

Visualization

Tap to expand
Count Equal and Divisible Pairs in an Array INPUT nums array (indices 0-6): 0 1 2 3 4 5 6 3 1 2 2 2 1 3 k = 2 Find pairs (i, j) where: 1. i < j 2. nums[i] == nums[j] 3. (i * j) % k == 0 Color Legend: Value 3 Value 1 Value 2 ALGORITHM STEPS 1 Group by Value Store indices for each value 2 Check All Pairs For same values, check i*j 3 Divisibility Test If (i*j) % k == 0, count++ 4 Return Count Total valid pairs found Valid Pairs Found: (0,6): nums=3,3 | 0*6=0 OK (2,3): nums=2,2 | 2*3=6 OK (2,4): nums=2,2 | 2*4=8 OK (3,4): nums=2,2 | 3*4=12 OK (1,5): 1*5=5 not divisible by 2 All products above % 2 == 0 FINAL RESULT Total Valid Pairs: 4 Pair Breakdown: (0,6): 3==3, 0*6=0%2=0 (2,3): 2==2, 2*3=6%2=0 (2,4): 2==2, 2*4=8%2=0 (3,4): 2==2, 3*4=12%2=0 Output: 4 Key Insight: Group indices by their values using a hash map. For each group, check all pairs (i,j) where i < j. Only pairs with equal values need divisibility check: if (i * j) % k == 0, increment counter. Time: O(n^2) worst case | Space: O(n) for grouping indices | Optimal for small arrays. TutorialsPoint - Count Equal and Divisible Pairs in an Array | Optimal Solution
Asked in
Google 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
567 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen