Problem Description
Given two positive integers left and right, identify two prime numbers num1 and num2 in the range [left, right] such that num2 - num1 is minimized. If there are multiple pairs with the same minimum difference, choose the pair with the smallest num1. If no such pair exists, return [-1, -1].
Key Insights
- Use the Sieve of Eratosthenes to efficiently generate all prime numbers up to right.
- Iterate only over the range from max(left, 2) to right to locate the primes.
- Track the previous encountered prime and update the best pair when a smaller gap between consecutive primes is found.
- Choose the pair with the smallest first prime in case of ties.
Space and Time Complexity
Time Complexity: O(n log log n) due to the Sieve of Eratosthenes, where n is right.
Space Complexity: O(n) for the sieve array.
Solution
The solution uses the Sieve of Eratosthenes to mark all prime numbers up to right. Starting from max(left, 2), we iterate through the range and identify primes. For each prime found, if we have a previous prime, we compute the gap and update the best pair if the gap is smaller than the current best. Finally, we return the best pair or [-1, -1] if less than two primes exist in the range.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java with line-by-line comments.