Number of Subarrays With LCM Equal to K Problem
#2470
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2470.
Given an integer array nums and an integer k, return the number of subarrays of nums where the least common multiple of the subarray's elements is k.
A subarray is a contiguous non-empty sequence of elements within an array.
The least common multiple of an array is the smallest positive integer that is divisible by all the array elements.
Example 1:
Input: nums = [3,6,2,7,1], k = 6
Output: 4
Explanation: The subarrays of nums where 6 is the least common multiple of all the subarray's elements are:
- [3,6,2,7,1]
- [3,6,2,7,1]
- [3,6,2,7,1]
- [3,6,2,7,1]
Example 2:
Input: nums = [3], k = 2
Output: 0
Explanation: There are no subarrays of nums where 2 is the least common multiple of all the subarray's elements.
Constraints:
1 <= nums.length <= 10001 <= nums[i], k <= 1000
Solution
Approach: Enumeration
Fix the left end of the subarray and extend it to the right, keeping the running LCM. Stop as soon as a value does not divide k, because the LCM would then no longer divide k. While extending, the LCM stays a divisor of k, so count every position where it equals k.
Complexity: O(n2) time and O(1) space, where n is the length of the array.
from math import gcd
class Solution:
def subarrayLCM(self, nums: List[int], k: int) -> int:
ans = 0
for i in range(len(nums)):
a = 1
for b in nums[i:]:
if k % b:
break
a = a // gcd(a, b) * b
ans += a == k
return ans