Closest Prime Numbers in Range - Problem
Given a range defined by two positive integers left and right, your task is to find the closest pair of prime numbers within this range.
You need to find two integers num1 and num2 such that:
left โค num1 < num2 โค right- Both
num1andnum2are prime numbers num2 - num1is minimized among all valid pairs
Return the array [num1, num2]. If multiple pairs have the same minimum difference, return the one with the smallest num1. If no such pair exists, return [-1, -1].
Example: In range [4, 6], we have primes 5. Since we need two different primes, return [-1, -1]. In range [4, 18], primes are [5, 7, 11, 13, 17]. The closest pairs are (5,7), (11,13) with difference 2. We return [5, 7] as it has smaller num1.
Input & Output
example_1.py โ Basic Case
$
Input:
left = 10, right = 19
โบ
Output:
[11, 13]
๐ก Note:
The primes in range [10, 19] are [11, 13, 17, 19]. The closest pairs are (11,13) and (17,19), both with difference 2. We return [11, 13] as it has the smaller first element.
example_2.py โ No Valid Pair
$
Input:
left = 4, right = 6
โบ
Output:
[-1, -1]
๐ก Note:
The only prime in range [4, 6] is 5. Since we need two different primes, no valid pair exists.
example_3.py โ Large Gaps
$
Input:
left = 20, right = 30
โบ
Output:
[23, 29]
๐ก Note:
The primes in range [20, 30] are [23, 29]. Only one pair exists: (23, 29) with difference 6.
Constraints
- 1 โค left โค right โค 106
- Both left and right are positive integers
- Important: If multiple pairs have the same minimum difference, return the one with the smallest num1 value
Visualization
Tap to expand
Understanding the Visualization
1
Sieve Creation
Mark all prime numbers using the sieve algorithm
2
Range Filtering
Extract only the primes within our target range
3
Minimum Gap
Find the consecutive pair with smallest difference
Key Takeaway
๐ฏ Key Insight: The closest prime pair will always be consecutive primes in the sorted list, so we only need to check adjacent pairs rather than all possible combinations!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code