Closest Prime Numbers in Range - Problem
Given two positive integers left and right, find the two integers num1 and num2 such that:
left <= num1 < num2 <= right- Both
num1andnum2are prime numbers num2 - num1is the minimum amongst all other pairs satisfying the above conditions
Return the positive integer array ans = [num1, num2]. If there are multiple pairs satisfying these conditions, return the one with the smallest num1 value. If no such numbers exist, return [-1, -1].
Input & Output
Example 1 — Basic Range
$
Input:
left = 4, right = 6
›
Output:
[5, 5]
💡 Note:
Only prime in range [4,6] is 5, but we need two different primes, so no valid pair exists. Wait, that's wrong. Let me recalculate: primes in [4,6] = [5]. Since we need num1 < num2, return [-1, -1]
Example 2 — Twin Primes
$
Input:
left = 4, right = 18
›
Output:
[11, 13]
💡 Note:
Primes in range: 5, 7, 11, 13, 17. Gaps: 7-5=2, 11-7=4, 13-11=2, 17-13=4. Minimum gap is 2, first occurrence is [11, 13]
Example 3 — Large Gap
$
Input:
left = 20, right = 30
›
Output:
[23, 29]
💡 Note:
Primes in range [20,30]: 23, 29. Only one pair possible: [23, 29] with gap 6
Constraints
- 1 ≤ left ≤ right ≤ 106
- Both left and right are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Input Range
Given range [left=4, right=18]
2
Find Primes
Locate all primes: 5, 7, 11, 13, 17
3
Calculate Gaps
Find minimum gap between consecutive primes
Key Takeaway
🎯 Key Insight: Use Sieve of Eratosthenes for efficient prime generation, then scan consecutive primes for minimum gap
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code