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 K INPUT nums array (indices 0-3) 2 i=0 6 i=1 4 i=2 3 i=3 k = 12 Prime Factorization: 12 = 2^2 × 3^1 Find pairs (i,j) where i < j and nums[i] * nums[j] % 12 == 0 GCD with k=12: gcd(2,12)=2, gcd(6,12)=6 gcd(4,12)=4, gcd(3,12)=3 ALGORITHM STEPS 1 Compute GCDs For each num, find gcd(num, k) 2 Count GCD frequencies Use hashmap for counts 3 Find valid GCD pairs g1 * g2 % k == 0 4 Count valid pairs Sum up pair counts Checking All Pairs: (0,1): 2*6=12 % 12=0 [OK] (0,2): 2*4=8 % 12=8 [X] (0,3): 2*3=6 % 12=6 [X] (1,2): 6*4=24 % 12=0 [OK] (1,3): 6*3=18 % 12=6 [X] (2,3): 4*3=12 % 12=0 [OK] Valid pairs: 3 FINAL RESULT Valid Pairs Found: Pair (0,1) 2 × 6 = 12 (div by 12) Pair (1,2) 6 × 4 = 24 (div by 12) Pair (2,3) 4 × 3 = 12 (div by 12) OUTPUT 3 Total valid pairs = 3 All products divisible by k=12 Key Insight: For optimal O(n × sqrt(k) + k) solution: Use GCD-based grouping. Two numbers a,b have product divisible by k iff gcd(a,k) × gcd(b,k) contains all prime factors of k. Group elements by their GCD with k, then count pairs between compatible GCD groups instead of checking all O(n^2) pairs directly. TutorialsPoint - Count Array Pairs Divisible by K | Optimal Solution
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