Problem Description
Given an integer array nums and a list of queries, for every possible pair (nums[i], nums[j]) with i < j compute the greatest common divisor (GCD). After sorting all these GCD values in ascending order, return for each query the element at the provided index in the sorted GCD pairs array.
Key Insights
- Directly computing all pairs is infeasible due to the potential 10^5 numbers leading to nearly 5e10 pairs.
- Use a frequency array to count occurrences of each number.
- For each potential divisor d, compute the total count of numbers in nums that are divisible by d, then determine the total pairs having a gcd that is a multiple of d.
- Utilize inclusion‐exclusion (or Mobius inversion style subtraction) to refine counts so that exactly those pairs whose GCD equals d are obtained.
- Aggregate counts for each d and then, since lower d values come first in the sorted order, build a cumulative frequency mapping to answer queries with binary search.
Space and Time Complexity
Time Complexity: O(m log m) where m is the maximum value in nums (up to 5 * 10^4) due to iterating over divisors and their multiples. Space Complexity: O(m) for frequency and count arrays.
Solution
We first count the frequency of every number in nums. For every candidate divisor d (from the maximum possible value down to 1), we sum the counts of its multiples to find how many numbers are divisible by d. The number of pairs with both numbers divisible by d is computed using combinatorics. However, these counts include pairs whose actual gcd is a multiple of d. We subtract the contributions from higher multiples of d to extract exactly the count for gcd equal to d. Finally, we prepare a cumulative frequency (or prefix sum) over these gcd counts (ordered in ascending order) to answer each query in O(log m) using binary search.