Number of Subarrays With GCD Equal to K — LeetCode 2447 Python Solution
- Problem
- #2447
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [9,3,1,2,6,3], k = 3
- Output
- 4
- Explanation
- The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are:
Python solution
class Solution:
def subarrayGCD(self, nums: List[int], k: int) -> int:
ans = 0
for i in range(len(nums)):
g = 0
for x in nums[i:]:
g = gcd(g, x)
ans += g == k
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times (n + \log M)), where n and M are the length of the array nums and the maximum value in the array nums, respectively |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2447. Number of Subarrays With GCD Equal to K is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2447. Number of Subarrays With GCD Equal to K?
- LeetCode 2447. Number of Subarrays With GCD Equal to K is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2447. Number of Subarrays With GCD Equal to K?
- The Python solution on this page runs in O(n \times (n + \log M)), where n and M are the length of the array nums and the maximum value in the array nums, respectively.
- What is the space complexity of LeetCode 2447. Number of Subarrays With GCD Equal to K?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2447. Number of Subarrays With GCD Equal to K cover?
- LeetCode 2447. Number of Subarrays With GCD Equal to K is tagged Array, Math and Number Theory on LeetCode.