Number of Subarrays With LCM Equal to K — LeetCode 2470 Python Solution
- Problem
- #2470
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- 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:
Python solution
class Solution:
def subarrayLCM(self, nums: List[int], k: int) -> int:
n = len(nums)
ans = 0
for i in range(n):
a = nums[i]
for b in nums[i:]:
x = lcm(a, b)
ans += x == k
a = x
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2470. Number of Subarrays With LCM Equal to K is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2470. Number of Subarrays With LCM Equal to K?
- LeetCode 2470. Number of Subarrays With LCM Equal to K is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2470. Number of Subarrays With LCM Equal to K?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 2470. Number of Subarrays With LCM Equal to K?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2470. Number of Subarrays With LCM Equal to K cover?
- LeetCode 2470. Number of Subarrays With LCM Equal to K is tagged Array, Math and Number Theory on LeetCode.