Longest Subarray With at Most K Distinct Prime Factors - Solution & Explanation
Practice this problemProblem Statement
You are given an integer array nums consisting of positive integers and an integer k.
The prime factor set of a subarray is the union of the distinct prime factors of all its elements.
Return the length of the longest subarray whose prime factor set contains at most k distinct prime factors. If no such subarray exists, return 0.
Example 1:
Input: nums = [7,6,10,12,11], k = 3
Output: 3
Explanation:
Consider the subarray [6, 10, 12]:
- The distinct prime factors of 6 are
{2, 3}. - The distinct prime factors of 10 are
{2, 5}. - The distinct prime factors of 12 are
{2, 3}. - The union of these sets is
{2, 3, 5}, which contains 3 distinct prime factors.
No longer subarray satisfies the condition. Therefore, the answer is 3.
Example 2:
Input: nums = [4,6,9,18], k = 4
Output: 4
Explanation:
Consider the entire array [4, 6, 9, 18]:
- The distinct prime factors of 4 are
{2}. - The distinct prime factors of 6 are
{2, 3}. - The distinct prime factors of 9 are
{3}. - The distinct prime factors of 18 are
{2, 3}. - The union of these sets is
{2, 3}, which contains 2 distinct prime factors.
Since 2 <= 4, the entire array is valid. Therefore, the answer is 4.
Example 3:
Input: nums = [6,10,15], k = 2
Output: 1
Explanation:
Every subarray of length at least 2 has prime factor set {2, 3, 5}, which contains 3 distinct prime factors.
Since 3 > 2, only subarrays of length 1 are valid. Therefore, the answer is 1.
Constraints:
1 <= nums.length <= 1052 <= nums[i] <= 1051 <= k <= 104
Approach Overview
Problem Overview: Given an array of positive integers, find the length of the longest contiguous subarray whose elements collectively have at most K distinct prime factors. A prime factor is counted once per subarray, not per element.
Approach 1: Brute Force - Check All Subarrays (O(n^2 * sqrt(m)))
Generate every possible subarray using two nested loops. For each subarray, factorize every element, insert all prime factors into a set, and check if the set size is at most K. Track the maximum length. This approach is straightforward but recomputes factorizations repeatedly, making it far too slow for large inputs. Space is O(n) in the worst case for the set of prime factors.
Approach 2: Preprocessing + Sliding Window (O(n * sqrt(m)) time, O(n) space)
Precompute the distinct prime factors for every element using trial division up to sqrt(m), where m is the maximum value in the array. Store these factor lists so each element is factorized only once. Then run a classic sliding window: expand the right pointer, add the current element's prime factors to a frequency map, and while the map size exceeds K, shrink the left pointer and remove factors that no longer appear in the window. The answer is the maximum window length seen. This is the optimal approach because it processes each element a constant number of times after preprocessing.
Approach 3: On-the-Fly Sliding Window with Cached Factorization (O(n * sqrt(m)) time, O(n) space)
Instead of precomputing all factor lists upfront, factorize each element lazily and cache the result in a hash map. This avoids factorizing elements that are never visited and can reduce constant factors when the array is large but the window is small. The sliding window logic remains identical. Prefer this when memory is tight or when many elements repeat.
Recommended for interviews: Interviewers expect the sliding window solution. Brute force shows you understand the problem, but the optimal solution demonstrates that you recognize the classic expand-and-shrink window pattern and can combine it with prime factorization. Mention that the frequency map tracks distinct prime factors, not element counts, and explain why a set alone cannot handle the shrinking step efficiently.
Related topics: Sliding Window, Hash Map, Math.
Solution
First, we preprocess the list of prime factors for every number in [2, 10^5] and store them in primes. Specifically, we enumerate i = 2, 3, cdots, M. If primes[i] is empty, then i is a prime, and we add i to the prime-factor list of every multiple of i.
Then we use a sliding window to find the longest valid subarray. A hash table cnt records the occurrence count of each prime factor in the current window. When the right pointer r expands, we add all prime factors of nums[r] to the window. When the number of distinct prime factors in the window exceeds k, the left pointer l shrinks and we remove the prime factors of nums[l]. Whenever the window is valid, we update the answer with the window length.
The time complexity is O(M log log M + n log M), and the space complexity is O(M log log M), where n is the length of nums and M = 10^5 is the maximum value of the array elements.
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force - Check All Subarrays | O(n^2 * sqrt(m)) | O(n) | Only for tiny arrays or verifying correctness |
| Preprocessing + Sliding Window | O(n * sqrt(m)) | O(n) | General case, best for interviews |
| On-the-Fly Sliding Window with Cached Factorization | O(n * sqrt(m)) | O(n) | When memory is constrained or many repeated elements |
Video Solutions (4)
Leetcode 4032 | Longest Subarray With at Most K Distinct Prime Factors | Leetcode weekly context 516
Frequently Asked Questions
Is Longest Subarray With at Most K Distinct Prime Factors easy or hard?
Longest Subarray With at Most K Distinct Prime Factors Python/Java solution
How to solve Longest Subarray With at Most K Distinct Prime Factors in O(n)?
What is the best approach for Longest Subarray With at Most K Distinct Prime Factors?
Is Longest Subarray With at Most K Distinct Prime Factors asked at Google/Amazon/Meta?
What data structure is used in Longest Subarray With at Most K Distinct Prime Factors?
What is the time complexity of Longest Subarray With at Most K Distinct Prime Factors?
Ready to solve this problem?
Practice Longest Subarray With at Most K Distinct Prime Factors with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor