Maximum Prime Difference - Problem

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.

The distance between two indices i and j is |i - j|.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Input & Output

Example 1 — Multiple Primes
$ Input: nums = [4,2,9,5,3]
Output: 3
💡 Note: Prime numbers are 2 (index 1), 5 (index 3), and 3 (index 4). Maximum distance is between indices 1 and 4: |4-1| = 3.
Example 2 — Same Prime Twice
$ Input: nums = [4,8,2,8]
Output: 0
💡 Note: Only one prime number 2 at index 2. Distance between the same index is 0.
Example 3 — Edge Positions
$ Input: nums = [2,4,6,8,11]
Output: 4
💡 Note: Primes are 2 (index 0) and 11 (index 4). Maximum distance is |4-0| = 4.

Constraints

  • 1 ≤ nums.length ≤ 3 × 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Maximum Prime Difference Single Pass - First and Last Prime Approach INPUT Array: nums 0 1 2 3 4 4 2 9 5 3 Prime Number Non-Prime Primes in array: 2 (idx:1), 5 (idx:3), 3 (idx:4) Goal: Find max distance between prime indices ALGORITHM STEPS 1 Initialize Variables firstPrime = -1, lastPrime = -1 2 Scan Array (L to R) Find first prime at index 1 4 2 ... first=1 3 Continue to End Track last prime at index 4 ... 5 3 last=4 4 Calculate Distance |lastPrime - firstPrime| |4 - 1| = 3 FINAL RESULT Distance Between Primes 4 2 idx:1 9 5 3 idx:4 Distance = 3 Calculation First Prime Index: 1 Last Prime Index: 4 OUTPUT 3 OK - Maximum Distance Found! Key Insight: Single pass optimization: Instead of storing all prime indices, we only need to track the FIRST and LAST prime positions. The maximum distance will always be between these two indices since any intermediate primes would result in smaller distances. Time Complexity: O(n), Space Complexity: O(1) TutorialsPoint - Maximum Prime Difference | Single Pass - First and Last Prime Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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