#3589
Count Prime-Gap Balanced Subarrays
MediumArrayMathQueueSliding WindowNumber TheoryMonotonic QueueHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a sliding window to efficiently track prime numbers and their max/min values, reducing the need for repeated calculations.
⚙️
Algorithm
3 steps- 1Step 1: Generate a list of primes in the array using the Sieve of Eratosthenes.
- 2Step 2: Use a sliding window to maintain the current subarray of primes and their max/min values.
- 3Step 3: Count valid subarrays where the difference between max and min is <= k.
solution.py20 lines
1def count_prime_gap_balanced(nums, k):
2 def sieve(n):
3 is_prime = [True] * (n + 1)
4 for i in range(2, int(n**0.5) + 1):
5 if is_prime[i]:
6 for j in range(i * i, n + 1, i):
7 is_prime[j] = False
8 return [i for i in range(2, n + 1) if is_prime[i]]
9 primes = sieve(max(nums))
10 prime_set = set(primes)
11 count = 0
12 left = 0
13 prime_window = []
14 for right in range(len(nums)):
15 if nums[right] in prime_set:
16 prime_window.append(nums[right])
17 while len(prime_window) > 1 and max(prime_window) - min(prime_window) > k:
18 prime_window.pop(0)
19 count += len(prime_window) - 1
20 return countℹ
Complexity note: The sliding window allows us to efficiently count subarrays in linear time.
- 1Understanding prime numbers is crucial.
- 2Sliding window technique optimizes subarray checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.