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
Sorted GCD Pair Queries INPUT nums array: 2 3 4 [0] [1] [2] queries array: 0 2 2 All pairs (i,j) where i < j: (2,3), (2,4), (3,4) GCD values: gcd(2,3)=1 gcd(2,4)=2 gcd(3,4)=1 ALGORITHM STEPS 1 Count Divisors Count freq of each num 2 Divisor Enumeration For each d, count pairs 3 Build gcdPairs Sort GCD values: [1,1,2] 4 Answer Queries Use prefix sum lookup Sorted gcdPairs: 1 1 2 [0] [1] [2] q[0]=0, q[1]=2, q[2]=2 FINAL RESULT Query Resolution: queries[0] = 0 gcdPairs[0] = 1 queries[1] = 2 gcdPairs[2] = 2 queries[2] = 2 gcdPairs[2] = 2 Output Array: 1 2 2 OK - Result: [1, 2, 2] All queries answered Key Insight: Instead of computing all O(n^2) pairs, use frequency counting with divisor enumeration. For each potential GCD value d, count how many numbers are divisible by d, then use inclusion-exclusion to get exact GCD counts. Build prefix sums for O(1) query lookup. TutorialsPoint - Sorted GCD Pair Queries | Frequency Counting with Divisor Enumeration
Asked in
Google 42 Meta 38 Amazon 35 Microsoft 28
25.0K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen