Magicsheet logo

Maximum Prime Difference

Medium
100%
Updated 8/1/2025

Asked by 1 Company

Maximum Prime Difference

1. What is this problem about?

The Maximum Prime Difference interview question is a combination of array traversal and number theory. You are given an array of integers, and you need to find the maximum distance (difference between indices) between any two prime numbers in the array. Essentially, you want to find the index of the first prime number and the index of the last prime number and calculate the absolute difference between them.

If there is only one prime or no primes, the difference is typically 0.

2. Why is this asked in interviews?

This Maximum Prime Difference coding problem tests two things: your ability to efficiently identify prime numbers and your ability to traverse arrays to find extremas. Companies like Unstop use it to see if you can implement a standard mathematical check (is_prime) and apply it within a simple optimization task. It also evaluates if you can optimize the prime check (e.g., checking up to square root) to ensure the overall solution is performant.

3. Algorithmic pattern used

The Array, Math, Number Theory interview pattern is applied here.

  1. Create a helper function to check if a number is prime. This function should iterate from 2 up to the square root of the number for efficiency.
  2. Traverse the array from the left to find the first index i where arr[i] is prime.
  3. Traverse the array from the right to find the last index j where arr[j] is prime.
  4. The result is j - i (if two or more primes are found).

4. Example explanation

Array: [4, 2, 9, 5, 3, 8, 10]

  1. Search from left:
    • 4 is not prime.
    • 2 is prime! (Index 1) -> first_prime_idx = 1.
  2. Search from right:
    • 10 is not prime.
    • 8 is not prime.
    • 3 is prime! (Index 4) -> last_prime_idx = 4.
  3. Difference: 4 - 1 = 3.

Maximum Prime Difference is 3.

5. Common mistakes candidates make

In the Maximum Prime Difference coding problem, candidates often forget that 1 is not a prime number. Another common mistake is using an inefficient prime-checking algorithm (like checking all divisors up to N), which can lead to TLE if the numbers in the array are very large. Some might also forget to handle the cases where there are zero or one prime numbers in the array.

6. Interview preparation tip

Always have a clean, optimized is_prime function in your toolkit. Remember: handle 0 and 1 as special cases, check 2 separately, and then loop through odd numbers up to the square root. This is a common sub-routine in many "Math + Array" interview questions.

Similar Questions