Number of Subarrays With LCM Equal to K — LeetCode 2470 Python Solution

MediumArrayMathNumber Theory
Problem
#2470
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview