2447. Number of Subarrays With GCD Equal to K
Explanation:
To solve this problem, we can iterate through all subarrays of the given array nums
and calculate the greatest common divisor (GCD) of each subarray. If the GCD of a subarray is equal to the given value k
, we increment the count of valid subarrays. We can calculate the GCD of a subarray efficiently using Euclidean algorithm. The time complexity of this approach is O(n^2 * log(max(nums))) where n is the length of the array nums
and max(nums) is the maximum value in the array. The space complexity is O(1).
class Solution {
public int countSubarraysWithGCD(int[] nums, int k) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
int curGcd = 0;
for (int j = i; j < nums.length; j++) {
curGcd = gcd(curGcd, nums[j]);
if (curGcd == k) {
count++;
}
}
}
return count;
}
private int gcd(int a, int b) {
return b == 0 ? a : 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.