Problem Description
Given an array of integers nums, find the maximum distance (difference in indices) between two prime numbers in the array. If only one prime exists, the answer is 0.
Key Insights
- Since nums[i] is at most 100, we can precompute the prime numbers up to 100.
- Iterate over the array and record the indices where the number is prime.
- The maximum distance is the difference between the last and first indices in the list of prime indices.
- If there is only one prime index, the maximum difference is 0.
Space and Time Complexity
Time Complexity: O(n) where n is the length of nums, since we iterate over the array once and checking for prime status is O(1) with precomputation. Space Complexity: O(n) in the worst-case scenario for storing indices of prime numbers.
Solution
We first precompute the set (or boolean lookup) of prime numbers from 1 to 100. Then, while scanning through the nums array, we gather the indices that correspond to primes. Finally, we calculate the maximum difference by subtracting the first prime index from the last prime index. This approach is efficient given the constraints, and by using a set for prime lookups, we ensure that each check is done in constant time.