Problem Description
Given an integer array nums and an integer k, count the number of pairs (i, j) (with i < j) such that the product nums[i] * nums[j] is divisible by k.
Key Insights
- Instead of checking every possible pair (which is O(n²)), transform each number by computing its greatest common divisor (gcd) with k.
- For a number num, let g = gcd(num, k). Notice that g will always be a divisor of k.
- The product nums[i] * nums[j] is divisible by k if and only if gcd(nums[i], k) * gcd(nums[j], k) is also divisible by k.
- Use a frequency map to count occurrences of each gcd value.
- Iterate over all pairs of these gcd values (taking care of duplicates) and count the valid pairs where the product of the two gcds is divisible by k.
- Since the number of divisors of k is small, this results in a significantly reduced number of iterations.
Space and Time Complexity
Time Complexity: O(n + m²), where n is the length of nums and m is the number of divisors of k (m is small in practice). Space Complexity: O(m), for storing the counts of each divisor which divides k.
Solution
We start by iterating through the nums array and computing gcd(num, k) for each number. This value is used to categorize the numbers by their contribution towards divisibility by k. With these categories, we then iterate over every pair of categories. For a pair of divisors (g1, g2) to yield a product divisible by k, the product g1 * g2 should be divisible by k. We add to the answer either by pairing numbers within the same category or across different categories, taking care to avoid overcounting.