#2470

Number of Subarrays With LCM Equal to K

Medium
ArrayMathNumber TheorySliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a sliding window technique to efficiently find subarrays with the desired LCM. By maintaining a window of elements, we can calculate the LCM incrementally, reducing the need for redundant calculations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter to zero and two pointers for the sliding window.
  2. 2Step 2: Expand the right pointer to include elements in the window and calculate the LCM.
  3. 3Step 3: If the LCM exceeds k, move the left pointer to shrink the window until the LCM is less than or equal to k.
  4. 4Step 4: If the LCM equals k, count all valid subarrays ending at the current right pointer.
  5. 5Step 5: Continue until all elements are processed.
solution.py24 lines
1# Full working Python code
2from math import gcd
3
4# Function to calculate LCM
5def lcm(a, b):
6    return a * b // gcd(a, b)
7
8# Main function to count subarrays with LCM equal to k
9def countSubarraysWithLCM(nums, k):
10    count = 0
11    n = len(nums)
12    left = 0
13    current_lcm = 1
14    for right in range(n):
15        current_lcm = lcm(current_lcm, nums[right])
16        while left <= right and current_lcm > k:
17            current_lcm = lcm(current_lcm, nums[left])
18            left += 1
19        if current_lcm == k:
20            count += (right - left + 1)
21    return count
22
23# Example usage
24print(countSubarraysWithLCM([3, 6, 2, 7, 1], 6))  # Output: 4

Complexity note: The time complexity is O(n) because we are using a single loop to traverse the array, and the LCM calculation is constant time due to the limited range of numbers. The space complexity is O(1) as we are using a constant amount of space.

  • 1Understanding the properties of LCM and how it relates to subarrays is crucial.
  • 2Using a sliding window technique can significantly reduce the time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.