3312. Sorted GCD Pair Queries You are given an integer array nums of length n and an…
- User
- Sorted GCD Pair Queries You are given an integer array nums of length n and an integer array queries. Let gdPairs denote an array obtained by calculating the GCD of all possible pairs (nums [1], nums [j ]), where then sorting these values in ascending order. For each query queries [1], you need to find the element at index queries [il in gdPairs. Return an integer array answer, where answer li] is the value at gedPairs [queries [ill for each query. The term gcd (a, b) denotes the greatest common divisor of a and b. < j< n, and Example 1: Input: nums = [2,3,4], queries = [0,2,2] Output: [1,2,2] Explanation: gdPairs = Igcd (nums [0], nums [1]), gcd (nums [0], nums [2]), gcd (nums [1], nums [2])] = [1, 2, 1]. After sorting in ascending order, gdPairs = [1, 1, 2]• So, the answer is [gdPairs [queries [0]], gdPairs [queries [11], gcdPairs [queries [2]]] = [1, 2, 21. Example 2: Input: nums = [4,4,2,11, queries = [5,3,1,0] Output: [4,2,1,1] Explanation: gdPairs 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 <= 105 • 1 <= nums [i] <= 5 * 104 • 1 <= queries. length <= 105 • 0 <= queries [i] < n * (n - 1) / 2. class Solution { public: vector gcdValues(vector& nums, vector& queries) {
}};
- Assistant
To solve this problem efficiently, we'll leverage the mathematical properties of the Greatest Common Divisor (GCD) and combinatorial counting principles.
Step 1: Count Frequencies First, we'll count the frequency of each number in the given
numsarray. Since the numbers are within a manageable range (up to (5 \times 10^4)), we can use an array (orunordered_mapfor sparsity) to keep track of occurrences.Step 2: Compute Counts of Numbers Divisible by k For each possible GCD value ( k ), we need to find out how many numbers in
numsare divisible by ( k ). We initialize an arraycnt[k]wherecnt[k]will represent the number of times a number divisible by ( k ) appears innums. This step is crucial for determining how many pairs can potentially have a GCD of ( k ).Step 3: Calculate Total Pairs for Each GCD Value For each possible GCD value ( k ), calculate the total number of pairs that have numbers divisible by ( k ) using the combination formula: [ \text{total_pairs}[k] = \frac{\text{cnt}[k] \times (\text{cnt}[k] - 1)}{2} ]
Step 4: Adjust Counts Using Inclusion-Exclusion Principle Not all pairs counted in the previous step will have a GCD exactly equal to ( k ); some may have a greater GCD that's a multiple of ( k ). We adjust the counts using the inclusion-exclusion principle: [ \text{total_pairs}[k] = \text{total_pairs}[k] - \sum_{m = 2k}^{\text{max_num}} \text{total_pairs}[m] ] This subtraction removes pairs counted multiple times.
Step 5: Prepare for Querying Now, we collect all GCD values where
total_pairs[k]is greater than 0. We sort these GCD values in ascending order and compute the cumulative counts (prefix sums) of their frequencies.Step 6: Answer Queries Using Binary Search For each query, we perform a binary search on the cumulative counts to find the corresponding GCD value. This works because the GCD values are sorted, and we have the cumulative frequency counts.
Implementation Details
- Data Types: We use
long longto handle large numbers since the counts and total pairs can be quite large (up to ( 1e10 )). - Efficiency: The total time complexity is ( O(\text{max_num} \log \text{max_num} + Q \log M) ), where ( Q ) is the number of queries and ( M ) is the number of unique GCD values.
- Edge Cases: Be careful with indices when performing the binary search and when building cumulative counts.
Below is the complete code implementing the above approach:
class Solution { public: vector<int> gcdValues(vector<int>& nums, vector<long long>& queries) { int max_num = 50000; vector<long long> counts(max_num + 1, 0); for (int num : nums) { counts[num]++; } vector<long long> cnt(max_num + 1, 0); // Compute cnt[k] = number of numbers divisible by k for (int k = 1; k <= max_num; ++k) { for (int m = k; m <= max_num; m += k) { cnt[k] += counts[m]; } } vector<long long> total_pairs(max_num + 1, 0); // Compute total_pairs[k] = number of pairs where GCD equals k for (int k = max_num; k >= 1; --k) { total_pairs[k] = cnt[k] * (cnt[k] - 1) / 2; for (int m = 2 * k; m <= max_num; m += k) { total_pairs[k] -= total_pairs[m]; } } // Collect GCD values and their frequencies vector<pair<int, long long>> gcd_freqs; for (int k = 1; k <= max_num; ++k) { if (total_pairs[k] > 0) { gcd_freqs.emplace_back(k, total_pairs[k]); } } // Build cumulative counts vector<long long> cumulative_counts; vector<int> gcd_values; long long cum_sum = 0; for (auto& p : gcd_freqs) { cum_sum += p.second; cumulative_counts.push_back(cum_sum); gcd_values.push_back(p.first); } // Answer queries vector<int> answer; for (long long q : queries) { // Find the smallest index j such that cumulative_counts[j] > q auto it = lower_bound(cumulative_counts.begin(), cumulative_counts.end(), q + 1); if (it != cumulative_counts.end()) { int idx = it - cumulative_counts.begin(); answer.push_back(gcd_values[idx]); } else { // This should not happen as queries are within valid range answer.push_back(-1); } } return answer; } };Explanation
- Counting Frequencies: We first count how many times each number occurs using an array
counts. - Computing Divisible Counts: We calculate
cnt[k], which holds the number of elements innumsdivisible byk. - Calculating Total Pairs: Using
cnt[k], we calculate the initial total pairs for each GCD value. - Adjusting with Inclusion-Exclusion: We adjust
total_pairs[k]by subtracting the counts of pairs with a higher GCD that is a multiple ofk. - Preparing GCD Frequencies: We collect all GCD values with their frequencies and compute the cumulative counts.
- Answering Queries: For each query, we use binary search to find the corresponding GCD value.
This solution efficiently handles large input sizes within the given constraints and provides the required output for each query.
- Data Types: We use