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
Subarrays With GCD Equal to K INPUT Array nums: 9 i=0 3 i=1 1 i=2 2 i=3 6 i=4 3 i=5 k = 3 Valid Subarrays: [9,3] GCD=3 [3] at i=1 GCD=3 [6,3] GCD=3 [3] at i=5 GCD=3 ALGORITHM STEPS 1 Iterate Start Index For each i from 0 to n-1 2 Expand Subarray For each j from i to n-1 3 Update Running GCD gcd = GCD(gcd, nums[j]) 4 Check and Count If gcd == k, count++ Early Termination: If gcd < k, break inner loop (GCD can only decrease) Example: i=0 GCD(9)=9, GCD(9,3)=3 [OK] GCD(9,3,1)=1 < 3 [break] FINAL RESULT Output: 4 Count Breakdown: [9,3]: GCD=3 count=1 [3](i=1): GCD=3 count=2 [6,3]: GCD=3 count=3 [3](i=5): GCD=3 count=4 Total: 4 [OK] Key Insight: GCD is monotonically non-increasing as we extend a subarray. Once GCD drops below k, it cannot increase again. This allows early termination of the inner loop, optimizing from pure O(n^2) to O(n^2) worst case but much faster in practice. Time: O(n^2 * log(max)), Space: O(1). TutorialsPoint - Number of Subarrays With GCD Equal to K | Optimized with Early GCD Calculation
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
485 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