Maximum Prime Difference - Problem
You're given an integer array nums and need to find the maximum distance between the indices of any two prime numbers in the array.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11 are prime numbers.
The distance between two indices i and j is calculated as |i - j|. You need to find all prime numbers in the array and return the maximum distance between any pair of their indices.
Example: In array [4, 2, 9, 5, 3], the prime numbers are at indices 1 (value 2), 3 (value 5), and 4 (value 3). The maximum distance is between indices 1 and 4, which is 4 - 1 = 3.
Input & Output
example_1.py โ Basic Case
$
Input:
[4, 2, 9, 5, 3]
โบ
Output:
3
๐ก Note:
Prime numbers are at indices 1 (value 2), 3 (value 5), and 4 (value 3). Maximum distance is between indices 1 and 4: 4 - 1 = 3.
example_2.py โ Multiple Primes
$
Input:
[2, 3, 5, 7, 11]
โบ
Output:
4
๐ก Note:
All numbers are prime. Maximum distance is between indices 0 and 4: 4 - 0 = 4.
example_3.py โ Single Prime
$
Input:
[4, 6, 8, 2]
โบ
Output:
0
๐ก Note:
Only one prime number (2 at index 3). Since we need at least two primes to calculate distance, return 0.
Constraints
- 1 โค nums.length โค 3 ร 105
- 1 โค nums[i] โค 106
- The array contains at least one prime number
- Follow-up: Can you solve this in O(n) time complexity?
Visualization
Tap to expand
Understanding the Visualization
1
Identify Lighthouses
Scan the coastline and mark all lighthouse positions (prime numbers)
2
Find Endpoints
The maximum sailing distance is between the leftmost and rightmost lighthouses
3
Calculate Distance
Return the difference between last and first lighthouse positions
Key Takeaway
๐ฏ Key Insight: Maximum distance between any two points on a line is always between the endpoints - no need to check intermediate pairs!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code