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
๐Ÿ” GCD Detective: Finding Subarrays with GCD = kTarget Array:931263Detective Process (k=3):[9,3] โ†’ GCD=3 โœ“[3] โ†’ GCD=3 โœ“[6,3] โ†’ GCD=3 โœ“[3] โ†’ GCD=3 โœ“๐ŸŽฏ Key Insight: GCD Never Increases!When extending subarrays, GCD can only stay same or decrease.This allows early termination when GCD < k, saving computation!
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

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
โœ“ 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
Asked in
Google 32 Amazon 28 Microsoft 24 Meta 18
23.4K Views
Medium Frequency
~18 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen