Longest Subarray With at Most K Distinct Prime Factors Problem
Description
LeetCode Problem 4032.
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 <= 10^52 <= nums[i] <= 10^51 <= k <= 10^4
Solution
Approach: Precomputed prime factors + sliding window
First list the distinct prime factors of every number up to 10^5: for each i from 2 up, if primes[i] is still empty then i is prime, so add i to primes[j] for every multiple j of i.
Then slide a window over nums. A hash map cnt stores, for each prime, how many numbers in the window contain it. Extending the right end adds the primes of nums[r]; while the map holds more than k primes, move the left end and remove the primes of nums[l]. Every window we stop at is valid, so the answer is the largest window length seen.
Complexity: time O(M log log M + n log M), space O(M log log M), where M = 10^5 is the largest value and n = nums.length.
mx = 100001
primes = [[] for _ in range(mx)]
for i in range(2, mx):
if not primes[i]:
for j in range(i, mx, i):
primes[j].append(i)
class Solution:
def longestSubarray(self, nums: List[int], k: int) -> int:
cnt = {}
ans = l = 0
for r, x in enumerate(nums):
for y in primes[x]:
cnt[y] = cnt.get(y, 0) + 1
while len(cnt) > k:
for y in primes[nums[l]]:
cnt[y] -= 1
if cnt[y] == 0:
del cnt[y]
l += 1
ans = max(ans, r - l + 1)
return ans