Approach
Breadth-first search
For Count Prime Gap Balanced Subarrays, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 54 lines of Python from the credited upstream file count-prime-gap-balanced-subarrays.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 5import collections6 7 89def linear_sieve_of_eratosthenes(n): 10 primes = []11 spf = [-1]*(n+1) 12 for i in xrange(2, n+1):13 if spf[i] == -1:14 spf[i] = i15 primes.append(i)16 for p in primes:17 if i*p > n or p > spf[i]:18 break19 spf[i*p] = p20 return spf21 22 23MAX_NUMS = 5*10**424SPF = linear_sieve_of_eratosthenes(MAX_NUMS)25class Solution(object):26 def primeSubarray(self, nums, k):27 """28 :type nums: List[int]29 :type k: int30 :rtype: int31 """32 idxs, max_dq, min_dq = collections.deque(), collections.deque(), collections.deque()33 result = left = 034 for right in xrange(len(nums)):35 if SPF[nums[right]] == nums[right]:36 idxs.append(right)37 while max_dq and nums[max_dq[-1]] <= nums[right]:38 max_dq.pop()39 max_dq.append(right)40 while min_dq and nums[min_dq[-1]] >= nums[right]:41 min_dq.pop()42 min_dq.append(right)43 while nums[max_dq[0]]-nums[min_dq[0]] > k:44 if min_dq[0] == left:45 min_dq.popleft()46 if max_dq[0] == left:47 max_dq.popleft()48 if idxs[0] == left:49 idxs.popleft()50 left += 151 if len(idxs) >= 2:52 result += idxs[-2]-left+153 return result54