Count Array Pairs Divisible by K Problem
#2183
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2183.
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 - 1andnums[i] * nums[j]is divisible byk.
Example 1:
Input: nums = [1,2,3,4,5], k = 2
Output: 7
Explanation:
The 7 pairs of indices whose corresponding products are divisible by 2 are
(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).
Their products are 2, 4, 6, 8, 10, 12, and 20 respectively.
Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.
Example 2:
Input: nums = [1,2,3,4], k = 5
Output: 0
Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5.
Constraints:
1 <= nums.length <= 10^51 <= nums[i], k <= 10^5
Solution
Approach: Group Numbers by GCD With k
Whether a * b is divisible by k depends only on gcd(a, k) and gcd(b, k): the product is divisible by k exactly when the product of the two gcds is. So replace every number by its gcd with k and count how many numbers share each value. There are at most as many distinct values as k has divisors, so we can try every pair of distinct values x < y with x * y divisible by k and add cnt[x] * cnt[y]. For equal values x, add cnt[x] * (cnt[x] - 1) / 2.
Complexity: O(n log k + d2) time, where d is the number of divisors of k (at most 128 for k up to 105), and O(d) space.
from collections import Counter
from math import gcd
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
cnt = Counter(gcd(x, k) for x in nums)
ans = 0
for x, c1 in cnt.items():
for y, c2 in cnt.items():
if x <= y and x * y % k == 0:
ans += c1 * c2 if x < y else c1 * (c1 - 1) // 2
return ans