Minimum Operations to Transform Array into Alternating Prime Problem
Description
LeetCode Problem 3896.
You are given an integer array nums.
An array is considered alternating prime if:
- Elements at even indices (0-based) are prime numbers.
- Elements at odd indices are non-prime numbers.
In one operation, you may increment any element by 1.
Return the minimum number of operations required to transform nums into an alternating prime 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,4]
Output: 3
Explanation:
- The element at index 0 must be prime. Increment nums[0] = 1 to 2, using 1 operation.
- The element at index 1 must be non-prime. Increment nums[1] = 2 to 4, using 2 operations.
- The element at index 2 is already prime.
- The element at index 3 is already non-prime.
Total operations = 1 + 2 = 3.
Example 2:
Input: nums = [5,6,7,8]
Output: 0
Explanation:
- The elements at indices 0 and 2 are already prime.
- The elements at indices 1 and 3 are already non-prime.
No operations are needed.
Example 3:
Input: nums = [4,4]
Output: 1
Explanation:
- The element at index 0 must be prime. Increment nums[0] = 4 to 5, using 1 operation.
- The element at index 1 is already non-prime.
Total operations = 1.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Preprocessing + Binary Search
Each position can be handled on its own, so we only need to know, for a single value, how many increments reach the nearest prime above it (even indices) or the nearest non-prime above it (odd indices).
Build a sieve once, giving a boolean array isPrime and the sorted list primes (up to 200000, which is safely beyond the next prime after 10^5). Then for every element:
- At an even index, binary search
primesfor the first prime>= xand add the difference to the answer. - At an odd index, if
xis prime we must move it to a non-prime. The next number is composite for every prime except2(3is prime, butx + 1is even and greater than 2 for any odd prime), so one increment is enough; for2we need two increments to reach4.
Complexity:
- Time complexity:
O(P log log P + n log P), wherePis the sieve limit andnthe array length. - Space complexity:
O(P).
from bisect import bisect_left
MX = 200000
is_prime = [True] * (MX + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(MX**0.5) + 1):
if is_prime[i]:
for j in range(i * i, MX + 1, i):
is_prime[j] = False
primes = [i for i in range(2, MX + 1) if is_prime[i]]
class Solution:
def minOperations(self, nums: List[int]) -> int:
ans = 0
for i, x in enumerate(nums):
if i % 2 == 0:
j = bisect_left(primes, x)
ans += primes[j] - x
else:
if is_prime[x]:
ans += 2 if x == 2 else 1
return ans