Problem Description
Given an integer array nums and an integer k, return the number of contiguous subarrays of nums where the least common multiple (LCM) of the subarray’s elements is equal to k.
Key Insights
- A valid subarray must consist only of numbers that are factors of k. If an element does not divide k, including it would introduce extra prime factors.
- Use a sliding window (nested loop) approach. For every starting index, extend the subarray and update the LCM until it matches k.
- Compute LCM using the formula: LCM(a, b) = (a * b) / GCD(a, b) and use the Euclidean algorithm for the GCD.
- Early break from the inner loop if an element does not divide k (or equivalently, if adding that element can no longer yield an LCM equal to k).
Space and Time Complexity
Time Complexity: O(n^2 * log(max(nums[i]))), where n is the length of nums, due to the nested loops and GCD computations. Space Complexity: O(1) additional space.
Solution
We iterate over each possible starting index of the subarray. For each start index, we maintain the current LCM of the subarray. For every new element, if the element is not a divisor of k, we break early because adding it would prevent the LCM from being k. We update the LCM using the formula LCM(a, b) = (a * b) / GCD(a, b). Whenever the updated LCM equals k, we increment our count.