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 num1 and num2 are prime numbers
  • num2 - num1 is 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.

Visualization

Tap to expand
Prime Treasure Hunt: Sieve Method๐Ÿ” Step 1: Sieve Detection11๐Ÿ’Ž12๐Ÿชจ13๐Ÿ’Ž14๐Ÿชจ15๐Ÿชจ16๐Ÿชจ17๐Ÿ’Ž๐Ÿ“Š Step 2: Collect Prime Gems111317๐Ÿ“ Step 3: Measure Adjacent Distancesdiff = 2diff = 4๐ŸŽฏ Winner: [11, 13] with minimum distance 2!
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!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log log n + k)

O(n log log n) for sieve where n=right, plus O(k) to scan k primes in range

n
2n
โšก Linearithmic
Space Complexity
O(n + k)

O(n) for sieve array, O(k) to store k primes in the range

n
2n
โšก Linearithmic Space

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
Asked in
Google 42 Amazon 38 Meta 28 Microsoft 24
42.8K Views
Medium-High Frequency
~25 min Avg. Time
1.3K 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