Number of Subarrays With GCD Equal to K - Problem
Given an integer array nums and an integer k, your task is to find how many contiguous subarrays have a greatest common divisor (GCD) equal to k.
A subarray is a contiguous sequence of elements within an array. The greatest common divisor (GCD) of an array is the largest positive integer that divides all elements in the array without remainder.
For example, if we have the array [9, 3, 1, 2, 6, 3] and k = 3, we need to count all subarrays where the GCD equals 3. The subarray [9, 3] has GCD = 3, while [3] also has GCD = 3.
Your goal: Return the total count of valid subarrays.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [9,3,1,2,6,3], k = 3
โบ
Output:
4
๐ก Note:
The subarrays with GCD equal to 3 are: [9,3] (GCD = 3), [3] at index 1 (GCD = 3), [6,3] (GCD = 3), and [3] at index 5 (GCD = 3). Total count = 4.
example_2.py โ Single Element
$
Input:
nums = [4], k = 7
โบ
Output:
0
๐ก Note:
The only subarray is [4] with GCD = 4, which is not equal to k = 7. Therefore, count = 0.
example_3.py โ All Same Elements
$
Input:
nums = [6,6,6], k = 6
โบ
Output:
6
๐ก Note:
All possible subarrays have GCD = 6: [6] (3 times), [6,6] (2 times), and [6,6,6] (1 time). Total = 3 + 2 + 1 = 6.
Visualization
Tap to expand
Understanding the Visualization
1
Position Detective
Start at each array position as a potential subarray beginning
2
Extend Investigation
Add one element at a time, updating the GCD incrementally
3
Track Discoveries
Count when GCD equals k, terminate when GCD drops below k
4
Optimize Search
Skip further extensions once GCD becomes too small
Key Takeaway
๐ฏ Key Insight: GCD can only decrease or stay the same when adding elements, enabling early termination optimization
Time & Space Complexity
Time Complexity
O(nยฒ log(min(nums)))
O(nยฒ) for nested loops, O(log(min)) for each GCD calculation
โ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 1 โค nums.length โค 1000
- 1 โค nums[i], k โค 109
- At least one element must be divisible by k for any valid subarray to exist
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code