Number of Subarrays With GCD Equal to K - Problem
Given an integer array nums and an integer k, return the number of subarrays of nums where the greatest common divisor of the subarray's elements is k.
A subarray is a contiguous non-empty sequence of elements within an array.
The greatest common divisor of an array is the largest integer that evenly divides all the array elements.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [9,3,1,2,6,3], k = 3
›
Output:
4
💡 Note:
The subarrays with GCD = 3 are: [9,3] (GCD=3), [3] at index 1 (GCD=3), [6,3] (GCD=3), [3] at index 5 (GCD=3). Total = 4 subarrays.
Example 2 — Single Element
$
Input:
nums = [4], k = 7
›
Output:
0
💡 Note:
Only one subarray [4] exists, but GCD(4) = 4 ≠ 7, so no valid subarrays.
Example 3 — All Elements Same
$
Input:
nums = [6,6,6], k = 6
›
Output:
6
💡 Note:
All subarrays have GCD = 6: [6], [6], [6], [6,6], [6,6], [6,6,6]. Total = 6 subarrays.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i], k ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums and target GCD value k
2
Process
Check all subarrays and calculate their GCD
3
Output
Count of subarrays with GCD = k
Key Takeaway
🎯 Key Insight: GCD can only decrease when extending subarrays, enabling early termination optimization
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code