- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 70 lines of C++ from the credited upstream file minimum-operations-to-transform-array-into-alternating-prime.cpp.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 5const auto& linear_sieve_of_eratosthenes = [](int n) { 6 vector<int> spf(n + 1, -1);7 vector<int> primes;8 for (int i = 2; i <= n; ++i) {9 if (spf[i] == -1) {10 spf[i] = i;11 primes.emplace_back(i);12 }13 for (const auto& p : primes) {14 if (i * p > n || p > spf[i]) {15 break;16 }17 spf[i * p] = p;18 }19 }20 return pair(primes, spf);21};22 23const int MAX_NUMS = 1e5 + 3;24const auto& [PRIMES, SPF] = linear_sieve_of_eratosthenes(MAX_NUMS);25 2627class Solution {28public:29 int minOperations(vector<int>& nums) {30 int result = 0;31 for (int i = 0; i < size(nums); ++i) {32 int x = nums[i];33 if (i % 2 == 0) {34 for (; SPF[x] != x; ++x) {35 ++result;36 }37 } else {38 for (; SPF[x] == x; ++x) {39 ++result;40 }41 }42 }43 return result;44 }45};46 4748495051class Solution2 {52public:53 int minOperations(vector<int>& nums) {54 int result = 0;55 for (int i = 0; i < size(nums); ++i) {56 const auto& x = nums[i];57 if (i % 2 == 0) {58 result += *lower_bound(cbegin(PRIMES), cend(PRIMES), x) - x;59 } else {60 if (x == 2) {61 result += 2;62 } else if (SPF[x] == x) {63 ++result;64 }65 }66 }67 return result;68 }69};70