LeetCode 2447: Number of Subarrays With GCD Equal to K Solution
Master LeetCode problem 2447 (Number of Subarrays With GCD Equal to K), a medium 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.
2447. Number of Subarrays With GCD Equal to K
Problem Explanation
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).
Solution Code
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);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2447 (Number of Subarrays With GCD Equal to K)?
This page provides optimized solutions for LeetCode problem 2447 (Number of Subarrays With GCD Equal to K) 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 2447 (Number of Subarrays With GCD Equal to K)?
The time complexity for LeetCode 2447 (Number of Subarrays With GCD Equal to K) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2447 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2447 in Java, C++, or Python.