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: 2
💡 Note: Equal value pairs: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). Only (1,2) with 1*2=2 and (0,3) with 0*3=0 are divisible by 3.

Constraints

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

Visualization

Tap to expand
Count Equal and Divisible Pairs: nums=[3,1,2,2,2,1,3], k=231222130123456k = 2, find pairs where nums[i] == nums[j] and (i * j) % 2 == 0Valid: (2,3), (2,4), (3,4) from value 2, (0,6) from value 3Output: 4 pairs found
Understanding the Visualization
1
Input
Array with values and divisor k
2
Process
Find pairs (i,j) where nums[i]==nums[j] and (i*j)%k==0
3
Output
Count of valid pairs
Key Takeaway
🎯 Key Insight: Only check pairs with equal values, then verify index product divisibility
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