#2523
Closest Prime Numbers in Range
MediumMathNumber TheorySieve of EratosthenesTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log log n)Space O(n)
Using the Sieve of Eratosthenes allows us to efficiently find all prime numbers up to 'right'. Then, we can simply iterate through the list of primes to find the closest pair.
⚙️
Algorithm
3 steps- 1Step 1: Use the Sieve of Eratosthenes to find all prime numbers up to 'right'.
- 2Step 2: Store the prime numbers in a list.
- 3Step 3: Iterate through the list of primes to find the pair with the minimum difference.
solution.py25 lines
1# Full working Python code
2
3def sieve_of_eratosthenes(n):
4 is_prime = [True] * (n + 1)
5 is_prime[0], is_prime[1] = False, False
6 for i in range(2, int(n**0.5) + 1):
7 if is_prime[i]:
8 for j in range(i * i, n + 1, i):
9 is_prime[j] = False
10 return [i for i in range(n + 1) if is_prime[i]]
11
12def closest_primes(left, right):
13 primes = sieve_of_eratosthenes(right)
14 filtered_primes = [p for p in primes if p >= left]
15 min_diff = float('inf')
16 ans = [-1, -1]
17 for i in range(len(filtered_primes) - 1):
18 diff = filtered_primes[i + 1] - filtered_primes[i]
19 if diff < min_diff:
20 min_diff = diff
21 ans = [filtered_primes[i], filtered_primes[i + 1]]
22 return ans
23
24# Example usage
25print(closest_primes(10, 19))ℹ
Complexity note: The Sieve of Eratosthenes runs in O(n log log n) time, which is efficient for finding all primes up to 'right'. The space complexity is O(n) due to the storage of the prime boolean array.
- 1Using efficient algorithms like the Sieve of Eratosthenes can drastically reduce computation time.
- 2Filtering primes after generating them allows for easy pair comparison.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.