Count Prime-Gap Balanced Subarrays Problem
Description
LeetCode Problem 3589.
You are given an integer array nums and an integer k.
A subarray is called prime-gap balanced if:
- It contains at least two prime numbers, and
- The difference between the maximum and minimum prime numbers in that subarray is less than or equal to
k.
Return the count of prime-gap balanced subarrays in nums.
Note:
- A subarray is a contiguous non-empty sequence of elements within an array.
- A prime number is a natural number greater than 1 with only two factors, 1 and itself.
Example 1:
Input: nums = [1,2,3], k = 1
Output: 2
Explanation:
Prime-gap balanced subarrays are:
- [2,3]: contains two primes (2 and 3), max - min = 3 - 2 = 1 <= k.
- [1,2,3]: contains two primes (2 and 3), max - min = 3 - 2 = 1 <= k.
Thus, the answer is 2.
Example 2:
Input: nums = [2,3,5,7], k = 3
Output: 4
Explanation:
Prime-gap balanced subarrays are:
- [2,3]: contains two primes (2 and 3), max - min = 3 - 2 = 1 <= k.
- [2,3,5]: contains three primes (2, 3, and 5), max - min = 5 - 2 = 3 <= k.
- [3,5]: contains two primes (3 and 5), max - min = 5 - 3 = 2 <= k.
- [5,7]: contains two primes (5 and 7), max - min = 7 - 5 = 2 <= k.
Thus, the answer is 4.
Constraints:
1 <= nums.length <= 5 * 10^41 <= nums[i] <= 5 * 10^40 <= k <= 5 * 10^4
Solution
Approach: Two Pointers with Monotonic Deques
Sieve the primes up to the largest value. Sweep the right end r, keeping the smallest valid left end left for which the primes inside [left, r] have a maximum minus minimum of at most k. Two monotonic deques over the primes in the window give that maximum and minimum, and left moves forward while the gap exceeds k. Removing elements never increases the gap, so left never needs to move back.
A subarray [l, r] with left <= l is balanced exactly when it contains at least two primes, i.e. when l is at most the position prev of the second-to-last prime at or before r. So each r adds prev - left + 1 subarrays when prev >= left.
Complexity: O(n + M log log M) time, where M is the largest value, and O(n + M) space.
from collections import deque
class Solution:
def primeSubarray(self, nums: List[int], k: int) -> int:
m = max(nums) + 1
is_prime = [True] * m
is_prime[0] = False
if m > 1:
is_prime[1] = False
for i in range(2, int(m ** 0.5) + 1):
if is_prime[i]:
for j in range(i * i, m, i):
is_prime[j] = False
max_q = deque()
min_q = deque()
ans = 0
left = 0
last = -1 # last prime position
prev = -1 # the prime position before it
for right, x in enumerate(nums):
if is_prime[x]:
while max_q and nums[max_q[-1]] <= x:
max_q.pop()
max_q.append(right)
while min_q and nums[min_q[-1]] >= x:
min_q.pop()
min_q.append(right)
prev, last = last, right
while nums[max_q[0]] - nums[min_q[0]] > k:
left += 1
if max_q[0] < left:
max_q.popleft()
if min_q[0] < left:
min_q.popleft()
if prev >= left:
ans += prev - left + 1
return ans