- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 61 lines of C++ from the credited upstream file count-prime-gap-balanced-subarrays.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 6 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 56vector<int> linear_sieve_of_eratosthenes(int n) { 7 vector<int> spf(n + 1, -1);8 vector<int> primes;9 for (int i = 2; i <= n; ++i) {10 if (spf[i] == -1) {11 spf[i] = i;12 primes.emplace_back(i);13 }14 for (const auto& p : primes) {15 if (i * p > n || p > spf[i]) {16 break;17 }18 spf[i * p] = p;19 }20 }21 return spf;22};23 24const int MAX_NUMS = 5 * 1e4;25const auto& SPF = linear_sieve_of_eratosthenes(MAX_NUMS);26class Solution {27public:28 int primeSubarray(vector<int>& nums, int k) {29 deque<int> idxs, max_dq, min_dq;30 int result = 0;31 for (int right = 0, left = 0; right < size(nums); ++right) {32 if (SPF[nums[right]] == nums[right]) {33 idxs.emplace_back(right);34 while (!empty(max_dq) && nums[max_dq.back()] <= nums[right]) {35 max_dq.pop_back();36 }37 max_dq.emplace_back(right);38 while (!empty(min_dq) && nums[min_dq.back()] >= nums[right]) {39 min_dq.pop_back();40 }41 min_dq.emplace_back(right);42 for (; nums[max_dq[0]] - nums[min_dq[0]] > k; ++left) {43 if (max_dq[0] == left) {44 max_dq.pop_front();45 }46 if (min_dq[0] == left) {47 min_dq.pop_front();48 }49 if (idxs[0] == left) {50 idxs.pop_front();51 }52 }53 }54 if (size(idxs) >= 2) {55 result += (idxs[size(idxs) - 2]) - left + 1;56 }57 }58 return result;59 }60};61