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
Prime 1Prime 2Prime 3Prime 4Maximum DistanceFirstLastThe optimal path always connects the first and last lighthouses
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!
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
24.7K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen