Count Array Pairs Divisible by K - Problem

Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:

  • 0 <= i < j <= n - 1 and
  • nums[i] * nums[j] is divisible by k.

A product is divisible by k if it contains all prime factors of k with at least the same frequency.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,6,4,3], k = 12
Output: 3
💡 Note: Valid pairs: (0,1) since 2×6=12 divisible by 12, (1,2) since 6×4=24 divisible by 12, and (2,3) since 4×3=12 divisible by 12
Example 2 — Smaller k
$ Input: nums = [1,2,3,4,5], k = 2
Output: 7
💡 Note: Products divisible by 2: 1×2=2, 1×4=4, 2×3=6, 2×5=10, 3×4=12, 4×5=20, plus any pair with an even number
Example 3 — All Same Numbers
$ Input: nums = [3,3,3], k = 9
Output: 3
💡 Note: All pairs (0,1), (0,2), (1,2) give product 3×3=9 which is divisible by 9

Constraints

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

Visualization

Tap to expand
Count Array Pairs Divisible by KFind pairs (i,j) where nums[i] × nums[j] is divisible by k2643index 0index 1index 2index 3k = 12Valid Pairs (products divisible by 12):Pair (0,1): 2 × 6 = 12 ✓Pair (1,2): 6 × 4 = 24 ✓Pair (2,3): 4 × 3 = 12 ✓Answer: 3 pairsChallenge: Do this efficiently without checking all O(n²) pairs
Understanding the Visualization
1
Input Array
Array nums and divisor k
2
Find Pairs
Check all pairs (i,j) where i < j
3
Count Valid
Count pairs where nums[i] × nums[j] % k == 0
Key Takeaway
🎯 Key Insight: Use GCD to group numbers by their useful factors, avoiding expensive product calculations
Asked in
Google 12 Meta 8 Apple 5
23.4K Views
Medium Frequency
~35 min Avg. Time
890 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