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
num1andnum2are prime numbers num2 - num1is 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
Visualization
Time & Space Complexity
O(n log log n) for sieve where n=right, plus O(k) to scan k primes in range
O(n) for sieve array, O(k) to store k primes in the range
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