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: [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
Closest Prime Numbers in Range [4, 18]Range:418Numbers 4 through 18Primes:57111317gap=2gap=4gap=2 ✓gap=4Minimum gap = 2, first occurrence between 11 and 13Result: [11, 13]
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
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