Taro Logo

Maximum Prime Difference

#1 Most AskedMedium
0 views
Topics:
ArraysTwo Pointers

You are given an integer array nums.

Return an integer that is the maximum distance between the indices of two (not necessarily different) prime numbers in nums.

Example 1:

Input: nums = [4,2,9,5,3]

Output: 3

Explanation: nums[1], nums[3], and nums[4] are prime. So the answer is |4 - 1| = 3.

Example 2:

Input: nums = [4,8,2,8]

Output: 0

Explanation: nums[2] is prime. Because there is just one prime number, the answer is |2 - 2| = 0.

Constraints:

  • 1 <= nums.length <= 3 * 105
  • 1 <= nums[i] <= 100
  • The input is generated such that the number of prime numbers in the nums is at least one.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be returned if the input array contains no prime numbers at all?
  2. Are numbers like 1, 0, or negative integers considered prime for the purposes of this problem?
  3. What are the constraints on the length of the array and the magnitude of the elements inside it?
  4. If there is only a single prime number in the array, should the absolute difference be considered zero (since its first and last occurrence are the same)?
  5. Can the input array contain duplicate prime numbers, and does 'first and last occurrences' refer to the very first index of *any* prime and the very last index of *any* (possibly different) prime, or are we tracking a specific prime?

Brute Force Solution

Approach

The problem asks for the maximum distance between the indices of any two prime numbers in an array. Since the values in the array are bounded by 100, we can identify primes using a lookup set. The maximum difference is simply the difference between the index of the last prime number and the index of the first prime number.

Here's how the algorithm would work step-by-step:

  1. Create a set containing all prime numbers between 1 and 100.
  2. Scan the array from the left to locate the first occurrence of a prime number.
  3. Scan the array from the right to locate the last occurrence of a prime number.
  4. Calculate the difference between the last prime index and the first prime index.
  5. Return the calculated difference as the result.

Code Implementation

def maximum_prime_difference(nums):
    # Predefine a set of all prime numbers up to 100
    prime_set = {
        2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
        31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
        73, 79, 83, 89, 97
    }
    
    # Find the index of the first prime number
    first_prime_index = -1
    for current_index, value in enumerate(nums):
        if value in prime_set:
            first_prime_index = current_index
            break
            
    # Find the index of the last prime number
    last_prime_index = -1
    for current_index in range(len(nums) - 1, -1, -1):
        if nums[current_index] in prime_set:
            last_prime_index = current_index
            break
            
    # Compute and return the maximum distance between prime indices
    return last_prime_index - first_prime_index

Big(O) Analysis

Time Complexity
O(n) – We iterate through the array of length n at most twice, and set membership checks for primes are O(1) operations.
Space Complexity
O(1) – Only a constant number of variables and a fixed-size set of primes up to 100 are used.

Optimal Solution

Approach

To find the maximum distance between prime numbers in a line of items, we can scan the line from both ends simultaneously to quickly spot the first and last primes. By finding the outermost primes from the left and right, we can instantly determine the furthest distance between any two primes without checking every single pair.

Here's how the algorithm would work step-by-step:

  1. Look at the sequence of items from the very beginning and keep going until you spot the first prime number.
  2. Mark the position of this first prime number.
  3. Look at the same sequence starting from the very end and move backward until you spot the first prime number from that direction.
  4. Mark the position of this last prime number.
  5. Measure the total distance or space between the first marked position and the last marked position.
  6. This straightforward boundary check gives you the maximum possible distance between any two prime numbers in the entire sequence.

Code Implementation

def maximum_prime_difference(integer_sequence):
    def is_number_prime(target_number):
        if target_number <= 1:
            return False
        for current_divisor in range(2, int(target_number**0.5) + 1):
            if target_number % current_divisor == 0:
                return False
        return True

    # Scan from the left to find the very first prime number in the sequence.
    left_prime_index = 0
    while left_prime_index < len(integer_sequence) and not is_number_prime(integer_sequence[left_prime_index]):
        left_prime_index += 1

    # Scan from the right to find the very last prime number in the sequence.
    right_prime_index = len(integer_sequence) - 1
    while right_prime_index >= 0 and not is_number_prime(integer_sequence[right_prime_index]):
        right_prime_index -= 1

    # Calculate the maximum distance by subtracting the outermost prime indices.
    return right_prime_index - left_prime_index

Big(O) Analysis

Time Complexity
O(n) – We scan the array of size n from the left to find the first prime number, which takes at most n operations in the worst case. Then, we independently scan the same array from the right to find the last prime number, taking at most another n operations. This leads to approximately 2n total operations in the worst case, where every element must be checked. By dropping the constant factor, the time complexity simplifies to O(n).
Space Complexity
O(1) – The algorithm only requires a few primitive integer variables to keep track of indices while scanning the sequence from both ends. Since no additional data structures, temporary arrays, or recursive calls are utilized, the extra memory consumed remains constant regardless of the input size N. Therefore, the auxiliary space complexity is O(1) because the memory footprint does not scale with the number of items in the sequence.

Edge Cases

Array containing no prime numbers
How to Handle:
The solution must safely handle the case where no primes are found to avoid invalid index subtraction.
Array with exactly one prime number
How to Handle:
When the first and last occurrence indices are identical, the absolute difference correctly evaluates to zero.
Array containing negative numbers and zero
How to Handle:
The prime checking helper function must correctly identify that numbers less than or equal to one are not prime.
Array containing composite numbers and boundary values like one
How to Handle:
The primality test must accurately filter out non-primes while correctly recognizing small primes like two and three.
Array where all elements are prime numbers
How to Handle:
The algorithm will find the very first index and the very last index of the array, maximizing the returned difference.
Extremely large arrays with maximum constraints
How to Handle:
A single linear scan through the array ensures optimal time complexity without exceeding memory or time limits.
Arrays with large integer values up to the constraint limits
How to Handle:
The primality test must use efficient square root trial division to prevent timeouts on large numbers.
Multiple identical prime numbers scattered across the array
How to Handle:
Tracking the absolute first and last index occurrences ensures the maximum distance is always calculated correctly.
0/1 completed