Number of Subarrays With LCM Equal to K - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,6,4], k = 6
Output: 2
💡 Note: The subarrays [6] and [2,6] have LCM equal to 6. LCM of [2,6,4] = 12, LCM of [6,4] = 12, LCM of [4] = 4.
Example 2 — Single Element
$ Input: nums = [4,4], k = 1
Output: 0
💡 Note: No subarray has LCM equal to 1. Both [4] and [4,4] have LCM = 4.
Example 3 — Multiple Matches
$ Input: nums = [3,6,2,3], k = 6
Output: 4
💡 Note: Subarrays with LCM = 6: [6], [3,6], [6,2], [3,6,2] all have LCM equal to 6.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i], k ≤ 1000

Visualization

Tap to expand
Number of Subarrays With LCM Equal to K INPUT Array nums: 2 idx 0 6 idx 1 4 idx 2 Target k: k = 6 Find count of subarrays where LCM equals k Subarrays: [2], [6], [4], [2,6], [6,4], [2,6,4] Total: 6 subarrays ALGORITHM STEPS 1 Iterate start index For each i: 0 to n-1 2 Expand subarray For each j: i to n-1 3 Compute LCM lcm = lcm(curr, nums[j]) 4 Check and count If lcm == k: count++ Incremental LCM Tracking: [2]: LCM=2 (not 6) [2,6]: LCM=6 (OK!) [2,6,4]: LCM=12 (not 6) [6]: LCM=6 (OK!) [6,4]: LCM=12 (not 6) [4]: LCM=4 (not 6) FINAL RESULT Valid Subarrays Found: [2, 6] LCM(2,6) = 6 [6] LCM(6) = 6 Output: 2 2 subarrays have LCM equal to k=6 OK - Verified Key Insight: Incremental LCM calculation avoids recomputing from scratch. LCM(a,b) = (a*b)/GCD(a,b). Once LCM exceeds k, we can break early since LCM only grows as we add elements. Time: O(n^2 * log(max)), Space: O(1). The optimization prunes unnecessary iterations. TutorialsPoint - Number of Subarrays With LCM Equal to K | Incremental LCM Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~15 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