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 num1 and num2 are prime numbers
  • num2 - num1 is 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: [-1, -1]
💡 Note: Only prime in range [4,6] is 5. Since we need two different primes with num1 < num2, no valid pair exists.
Example 2 — Twin Primes
$ Input: left = 4, right = 18
Output: [5, 7]
💡 Note: Primes in range [4,18]: 5, 7, 11, 13, 17. Gaps between consecutive primes: 7-5=2, 11-7=4, 13-11=2, 17-13=4. Minimum gap is 2, first occurrence is [5, 7]
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
Closest Prime Numbers in Range INPUT 1 2 3 4 5 6 7 8 Range [4, 6] Prime Composite Out of range Input Parameters: left = 4 right = 6 ALGORITHM STEPS 1 Sieve of Eratosthenes Mark primes up to right 4 5 6 2 Collect Primes In range [left, right] primes = [5] 3 Linear Scan Find min gap pairs Only 1 prime found! 4 Edge Case Less than 2 primes Return special case FINAL RESULT Prime analysis in [4, 6]: 4 2x2 5 PRIME 6 2x3 Only ONE prime in range! Need at least 2 primes to form a pair Output: [-1, -1] No valid pair exists (Expected output was [5,5] but that's invalid) Key Insight: The Sieve of Eratosthenes efficiently marks all primes up to 'right' in O(n log log n) time. Then a linear scan finds consecutive primes with minimum gap. Twin primes (gap=2) are optimal when they exist. Note: num1 must be strictly less than num2, so [5,5] is actually invalid! TutorialsPoint - Closest Prime Numbers in Range | Sieve of Eratosthenes + Linear Scan
Asked in
Google 25 Microsoft 20 Amazon 15
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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