LeetCode 3312: Sorted GCD Pair Queries Solution

Master LeetCode problem 3312 (Sorted GCD Pair Queries), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

  • Algorithmic Idea:

    1. Calculate the GCD of all possible pairs of elements from the array nums.
    2. Sort the GCD values in ascending order to get gcdPairs.
    3. For each query, return the value at the specified index in gcdPairs.
  • Step-by-Step Iterations:

    1. Calculate the GCD of all pairs: loop over all pairs of elements and calculate their GCD.
    2. Sort the GCD values in ascending order.
    3. For each query, return the value at the specified index in the sorted GCD pairs.
  • Time Complexity: O(n^2 * log(max(nums)))

  • Space Complexity: O(n^2)

:

Solution Code

class Solution {
    public int[] gcdSort(int[] nums, int[] queries) {
        int n = nums.length;
        List<Integer> gcdPairs = new ArrayList<>();
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                gcdPairs.add(gcd(nums[i], nums[j]));
            }
        }
        
        Collections.sort(gcdPairs);
        
        int[] answer = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            answer[i] = gcdPairs.get(queries[i]);
        }
        
        return answer;
    }
    
    private int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3312 (Sorted GCD Pair Queries)?

This page provides optimized solutions for LeetCode problem 3312 (Sorted GCD Pair Queries) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3312 (Sorted GCD Pair Queries)?

The time complexity for LeetCode 3312 (Sorted GCD Pair Queries) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3312 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3312 in Java, C++, or Python.

Back to LeetCode Solutions