#3115
Maximum Prime Difference
MediumArrayMathNumber TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking every pair, we can simply find the first and last occurrence of prime numbers in the array. The distance between these two indices will give us the maximum distance.
⚙️
Algorithm
3 steps- 1Step 1: Initialize variables to store the first and last index of a prime number.
- 2Step 2: Iterate through the array to find prime numbers and update the first and last index accordingly.
- 3Step 3: Calculate the distance between the first and last index of prime numbers.
solution.py22 lines
1# Full working Python code
2
3def is_prime(num):
4 if num < 2:
5 return False
6 for i in range(2, int(num**0.5) + 1):
7 if num % i == 0:
8 return False
9 return True
10
11def max_prime_distance(nums):
12 first_index = -1
13 last_index = -1
14 for i in range(len(nums)):
15 if is_prime(nums[i]):
16 if first_index == -1:
17 first_index = i
18 last_index = i
19 return last_index - first_index
20
21# Example usage
22print(max_prime_distance([4, 2, 9, 5, 3]))ℹ
Complexity note: The time complexity is O(n) because we only need to make a single pass through the array to find the first and last prime indices. The space complexity is O(1) since we are using a fixed amount of space for variables.
- 1Finding the first and last occurrence of primes is more efficient than checking all pairs.
- 2The problem can be simplified by focusing on indices instead of values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.