Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Operations to Transform Array into Alternating Prime solution and explanation

MediumArrayBinary SearchMathNumber Theory5 min read53.2% acceptanceUpdated 27 Jul 2026
Leetcode 3896 | Minimum Operations to Transform Array into Alternating PrimeCodeWithMeGuys · 13:06 · 184 viewsWatch on YouTube
2 more videos on this problem
  1. Leetcode 3896 | Minimum Operations to Transform Array into Alternating PrimeCodeWithMeGuys · 13:06 · 184 views
  2. Minimum Operations to Transform Array into Alternating Prime | Leetcode 3896 | Explanation With Codecodewithsitaram · 21:43 · 125 views
  3. Minimum Operations to Transform Array into Alternating Prime | LeetCode Q3 | JavaBreakingCode · 16:22 · 32 views

The problem

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 <= 105
  • 1 <= nums[i] <= 105

Approach overview

Problem Overview: You are given an array of integers and must transform it into an alternating pattern involving prime numbers. Each operation modifies an element (typically by incrementing or decrementing its value) so that the final array alternates between prime and non‑prime values. The goal is to minimize the total number of operations.

Approach 1: Brute Force Prime Adjustment (O(n * sqrt(V)) time, O(1) space)

Check both possible alternating patterns: prime at even indices and non‑prime at odd indices, or the reverse. For each element, determine whether it already satisfies the required state (prime or non‑prime). If not, compute the minimum number of increments or decrements required to reach the nearest valid number. Primality is checked using trial division up to sqrt(num). This approach is straightforward and useful for smaller value ranges but becomes slow when many prime checks are required.

Approach 2: Precompute Primes with Sieve (O(V log log V + n) time, O(V) space)

Instead of checking primality repeatedly, precompute all primes up to the maximum value range using the Sieve of Eratosthenes. Store them in a boolean array so prime checks become O(1). Then evaluate both alternating patterns by iterating through the array once and computing the minimal distance to a valid prime or non‑prime value when needed. Precomputation removes the repeated sqrt(V) checks and significantly speeds up the evaluation when the array is large.

Approach 3: Greedy Pattern Evaluation (O(n) time after preprocessing, O(V) space)

After building the prime lookup table, iterate through the array while maintaining the expected state (prime or non‑prime) for the current index. If the element already matches the requirement, move forward. Otherwise compute the nearest valid value and add the adjustment cost. Run this process twice—once assuming index 0 should be prime and once assuming it should be non‑prime—and take the minimum result. The greedy insight is that each position can be optimized independently once the pattern is fixed.

Recommended for interviews: The sieve + greedy evaluation approach. Interviewers expect you to reduce repeated prime checks and reason about evaluating two possible patterns. Mention the brute force method first to show baseline reasoning, then optimize with precomputation. This combines concepts from arrays, math, and number theory.

Solution

We can first preprocess a sufficiently large list of prime numbers, denoted as primes, and a boolean array isPrime, where isPrime[i] indicates whether i is a prime number.

Then we traverse each element in the array:

  • If the index of the current element is even, we need to increase it to the next prime number. We can use binary search on primes to find the first prime number greater than or equal to the current element, and add the difference between them to the answer.
  • If the index of the current element is odd and the current element is prime, we need to increase it to the next non-prime number. For the prime number 2, we need 2 increments to reach the next non-prime number 4; for other prime numbers, we only need 1 increment to reach the next non-prime number.

Finally, return the answer.

The time complexity is O(n times log P), and the space complexity is O(P). Here, n and P are the length of the array and the length of the preprocessed prime list, respectively.

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
class Solution {
    private static final int MX = 200000;
    private static final boolean[] IS_PRIME = new boolean[MX + 1];
    private static final List<Integer> PRIMES = new ArrayList<>();

    static {
        Arrays.fill(IS_PRIME, true);
        IS_PRIME[0] = false;
        IS_PRIME[1] = false;
        for (int i = 2; i <= MX / i; ++i) {
            if (IS_PRIME[i]) {
                for (int j = i * i; j <= MX; j += i) {
                    IS_PRIME[j] = false;
                }
            }
        }
        for (int i = 2; i <= MX; ++i) {
            if (IS_PRIME[i]) {
                PRIMES.add(i);
            }
        }
    }

    public int minOperations(int[] nums) {
        int ans = 0;
        for (int i = 0; i < nums.length; ++i) {
            int x = nums[i];
            if ((i & 1) == 0) {
                int j = Collections.binarySearch(PRIMES, x);
                if (j < 0) {
                    j = -j - 1;
                }
                ans += PRIMES.get(j) - x;
            } else if (IS_PRIME[x]) {
                ans += x == 2 ? 2 : 1;
            }
        }
        return ans;
    }
}
class Solution {
public:
    int minOperations(vector<int>& nums) {
        int ans = 0;
        for (int i = 0; i < nums.size(); ++i) {
            int x = nums[i];
            if ((i & 1) == 0) {
                auto it = lower_bound(primes.begin(), primes.end(), x);
                ans += *it - x;
            } else if (isPrime[x]) {
                ans += x == 2 ? 2 : 1;
            }
        }
        return ans;
    }

private:
    static constexpr int MX = 200000;
    inline static vector<bool> isPrime = [] {
        vector<bool> p(MX + 1, true);
        p[0] = p[1] = false;
        for (int i = 2; i <= MX / i; ++i) {
            if (p[i]) {
                for (int j = i * i; j <= MX; j += i) {
                    p[j] = false;
                }
            }
        }
        return p;
    }();

    inline static vector<int> primes = [] {
        vector<int> res;
        for (int i = 2; i <= MX; ++i) {
            if (isPrime[i]) {
                res.push_back(i);
            }
        }
        return res;
    }();
};
const MX = 200000;

const isPrime: boolean[] = (() => {
    const p = Array<boolean>(MX + 1).fill(true);
    p[0] = p[1] = false;
    for (let i = 2; i <= Math.floor(MX / i); ++i) {
        if (p[i]) {
            for (let j = i * i; j <= MX; j += i) {
                p[j] = false;
            }
        }
    }
    return p;
})();

const primes: number[] = Array.from({ length: MX - 1 }, (_, i) => i + 2).filter(i => isPrime[i]);

function minOperations(nums: number[]): number {
    let ans = 0;
    for (let i = 0; i < nums.length; ++i) {
        const x = nums[i];
        if ((i & 1) === 0) {
            const j = _.sortedIndex(primes, x);
            ans += primes[j] - x;
        } else if (isPrime[x]) {
            ans += x === 2 ? 2 : 1;
        }
    }
    return ans;
}
const MX = 200000

var isPrime = func() []bool {
	p := make([]bool, MX+1)
	for i := range p {
		p[i] = true
	}
	p[0], p[1] = false, false
	for i := 2; i <= MX/i; i++ {
		if p[i] {
			for j := i * i; j <= MX; j += i {
				p[j] = false
			}
		}
	}
	return p
}()

var primes = func() []int {
	var res []int
	for i := 2; i <= MX; i++ {
		if isPrime[i] {
			res = append(res, i)
		}
	}
	return res
}()

func minOperations(nums []int) (ans int) {
	for i, x := range nums {
		if i%2 == 0 {
			j := sort.SearchInts(primes, x)
			ans += primes[j] - x
		} else if isPrime[x] {
			if x == 2 {
				ans += 2
			} else {
				ans++
			}
		}
	}
	return
}
Try this approach in the editor

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force Prime AdjustmentO(n * sqrt(V))O(1)Small input values where repeated prime checks are cheap
Sieve + Pattern SimulationO(V log log V + n)O(V)General case when array size is large and fast prime lookup is needed
Greedy Alternating EvaluationO(n)O(V)Best choice after sieve preprocessing; optimal for interview solutions

Frequently asked questions

Is Minimum Operations to Transform Array into Alternating Prime easy or hard?

The problem is typically classified as Medium because it combines multiple concepts: prime detection, greedy evaluation, and handling two possible alternating patterns. The implementation itself is straightforward once you precompute primes efficiently.

Minimum Operations to Transform Array into Alternating Prime Python/Java solution

Implement a sieve to mark primes up to the maximum possible value, then iterate through the array twice for the two possible alternating patterns. Each pass accumulates the cost to convert elements to the required prime or non‑prime state. The same logic works in Python, Java, and C++ with minor syntax differences.

How to solve Minimum Operations to Transform Array into Alternating Prime in O(n)?

After precomputing primes with the Sieve of Eratosthenes, iterate through the array once while enforcing the expected pattern (prime or non‑prime). Compute adjustment cost when the element violates the pattern. Run the process for both possible starting patterns and return the minimum cost, resulting in O(n) traversal after preprocessing.

What is the best approach for Minimum Operations to Transform Array into Alternating Prime?

The most efficient approach uses a Sieve of Eratosthenes to precompute prime numbers and then evaluates two alternating patterns: prime at even indices or prime at odd indices. For each element, calculate the minimal adjustment needed to satisfy the required state. This reduces repeated primality checks and runs in O(V log log V + n) time.

Is Minimum Operations to Transform Array into Alternating Prime asked at Google/Amazon/Meta?

Problems involving prime checks, alternating constraints, and minimal transformations commonly appear in coding interviews at large tech companies. Variations combining arrays with number theory or greedy pattern evaluation are typical in Google and Amazon style interview rounds.

What data structure is used in Minimum Operations to Transform Array into Alternating Prime?

The core data structure is a boolean array or list used for the Sieve of Eratosthenes to store prime information. This allows constant‑time prime checks while iterating through the input array and computing transformation costs.

What is the time complexity of Minimum Operations to Transform Array into Alternating Prime?

The brute force solution runs in O(n * sqrt(V)) because each element may require a trial‑division prime check. Using a sieve to precompute primes reduces repeated checks and improves the complexity to O(V log log V + n), where V is the maximum value considered for prime computation.

Comments

Now write it yourselfClose this page and solve Minimum Operations to Transform Array into Alternating Prime in the editor, without looking.
Practise Minimum Operations to Transform Array into Alternating Prime