3312. Sorted GCD Pair Queries
Explanation:
-
Algorithmic Idea:
- Calculate the GCD of all possible pairs of elements from the array
nums
. - Sort the GCD values in ascending order to get
gcdPairs
. - For each query, return the value at the specified index in
gcdPairs
.
- Calculate the GCD of all possible pairs of elements from the array
-
Step-by-Step Iterations:
- Calculate the GCD of all pairs: loop over all pairs of elements and calculate their GCD.
- Sort the GCD values in ascending order.
- 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)
:
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);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.