Number of Subarrays With LCM Equal to K - Problem

Given an integer array nums and an integer k, return the number of subarrays where the least common multiple (LCM) of all elements in the subarray equals k.

A subarray is a contiguous non-empty sequence of elements within an array. For example, in array [1,2,3,4], the subarrays include [1], [1,2], [2,3,4], etc.

The least common multiple (LCM) of an array is the smallest positive integer that is divisible by all elements in the array. For instance, LCM of [2,3] is 6, and LCM of [4,6] is 12.

Challenge: Find all contiguous subarrays whose LCM equals exactly k!

Input & Output

example_1.py โ€” Basic Example
$ Input: nums = [1,2,3], k = 6
โ€บ Output: 1
๐Ÿ’ก Note: Only the subarray [2,3] has LCM equal to 6. LCM(2,3) = 6.
example_2.py โ€” Multiple Subarrays
$ Input: nums = [3,6,2,7,1], k = 6
โ€บ Output: 4
๐Ÿ’ก Note: The subarrays with LCM equal to 6 are: [6], [3,2], [2,3], and [6] (if 6 appears multiple times).
example_3.py โ€” Single Element
$ Input: nums = [3], k = 3
โ€บ Output: 1
๐Ÿ’ก Note: The only subarray [3] has LCM equal to 3.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค nums[i], k โ‰ค 1000
  • All elements are positive integers

Visualization

Tap to expand
23412Array: [2, 3, 4, 12], k = 6[2]LCM=2[2,3]LCM=6 โœ“[2,3,4]LCM=12 > 6STOP!Count: 1
Understanding the Visualization
1
Start Fresh
Begin with each array element as a potential starting point
2
Extend Gradually
Add one ingredient (element) at a time, updating the serving count (LCM)
3
Check Target
If serving count equals target k, count this combination
4
Smart Stop
If serving count exceeds k, stop extending - no point in adding more ingredients
Key Takeaway
๐ŸŽฏ Key Insight: LCM only increases or stays same when adding elements, allowing early termination optimization
Asked in
Google 25 Meta 18 Microsoft 15 Amazon 12
23.3K Views
Medium Frequency
~18 min Avg. Time
847 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