Sorted GCD Pair Queries - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,3,4], queries = [0,2,2]
›
Output:
[1,2,2]
💡 Note:
All pairs: (2,3)→gcd=1, (2,4)→gcd=2, (3,4)→gcd=1. Sorted gcdPairs = [1,1,2]. Query results: gcdPairs[0]=1, gcdPairs[2]=2, gcdPairs[2]=2
Example 2 — Duplicates
$
Input:
nums = [4,4,2,1], queries = [5,3,1,0]
›
Output:
[4,2,1,1]
💡 Note:
All pairs: (4,4)→gcd=4, (4,2)→gcd=2, (4,1)→gcd=1, (4,2)→gcd=2, (4,1)→gcd=1, (2,1)→gcd=1. Sorted gcdPairs = [1,1,1,2,2,4]. Results: [4,2,1,1]
Example 3 — Small Array
$
Input:
nums = [6,9], queries = [0]
›
Output:
[3]
💡 Note:
Only one pair: (6,9)→gcd=3. So gcdPairs = [3] and gcdPairs[0] = 3
Constraints
- 2 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 5 × 104
- 1 ≤ queries.length ≤ 105
- 0 ≤ queries[i] < nums.length × (nums.length - 1) / 2
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums and queries to answer
2
Generate GCD Pairs
Calculate GCD for all pairs (i,j) where i < j
3
Sort & Query
Sort GCD values and answer queries by indexing
Key Takeaway
🎯 Key Insight: Transform the problem from pair generation to frequency counting for efficiency
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code