Sorted GCD Pair Queries Problem
Description
LeetCode Problem 3312.
You are given an integer array nums of length n and an integer array queries.
Let gcdPairs denote an array obtained by calculating the GCD of all possible pairs (nums[i], nums[j]), where 0 <= i < j < n, and then sorting these values in ascending order.
For each query queries[i], you need to find the element at index queries[i] in gcdPairs.
Return an integer array answer, where answer[i] is the value at gcdPairs[queries[i]] for each query.
The term gcd(a, b) denotes the greatest common divisor of a and b.
Example 1:
Input: nums = [2,3,4], queries = [0,2,2]
Output: [1,2,2]
Explanation:
gcdPairs = [gcd(nums[0], nums[1]), gcd(nums[0], nums[2]), gcd(nums[1], nums[2])] = [1, 2, 1].
After sorting in ascending order, gcdPairs = [1, 1, 2].
So, the answer is [gcdPairs[queries[0]], gcdPairs[queries[1]], gcdPairs[queries[2]]] = [1, 2, 2].
Example 2:
Input: nums = [4,4,2,1], queries = [5,3,1,0]
Output: [4,2,1,1]
Explanation:
gcdPairs sorted in ascending order is [1, 1, 1, 2, 2, 4].
Example 3:
Input: nums = [2,2], queries = [0,0]
Output: [2,2]
Explanation:
gcdPairs = [2].
Constraints:
2 <= n == nums.length <= 10^51 <= nums[i] <= 5 * 10^41 <= queries.length <= 10^50 <= queries[i] < n * (n - 1) / 2
Solution
Approach: Count Pairs per GCD, Prefix Sums, Binary Search
Let cntG[i] be the number of pairs whose GCD is exactly i. Process i from the largest value mx down to 1:
- Let
vbe how many elements ofnumsare multiples ofi. Any two of them have a GCD that is a multiple ofi, so there arev * (v - 1) / 2such pairs. - Some of those pairs have a GCD that is a larger multiple
jofi; subtractcntG[j]for every multiplej > iofi. They are already computed because we go from large to small.
The prefix sums of cntG tell how many pairs have GCD at most i. The element at index q of the sorted GCD list is the first i whose prefix sum is greater than q, found by binary search.
Complexity: O(n + (M + q) log M) time and O(M) space, where M is the maximum of nums and q the number of queries.
from bisect import bisect_right
from collections import Counter
from itertools import accumulate
class Solution:
def gcdValues(self, nums: List[int], queries: List[int]) -> List[int]:
mx = max(nums)
cnt = Counter(nums)
cnt_g = [0] * (mx + 1)
for i in range(mx, 0, -1):
v = 0
for j in range(i, mx + 1, i):
v += cnt[j]
cnt_g[i] -= cnt_g[j]
cnt_g[i] += v * (v - 1) // 2
s = list(accumulate(cnt_g))
return [bisect_right(s, q) for q in queries]