Find the pair of prime numbers within a given interval whose difference is smallest.
Closest Prime Numbers in Range
Given two integers left and right, consider all prime numbers in the inclusive range [left, right].
Return the pair of primes with the smallest absolute difference. If there are multiple pairs with the same minimum difference, return the pair with the smaller first prime.
If fewer than two prime numbers exist in the range, return [-1, -1].
A number is prime if it has exactly two positive divisors: 1 and itself.
Input Format
- Two integers
leftandrightdescribing an inclusive range. - You may assume
left <= right.
Output Format
- Return two integers representing the closest pair of primes in the range.
- If no valid pair exists, return
[-1, -1].
Constraints
1 <= left <= right- The range may be large enough that checking each number naively is inefficient.
- Prime numbers are integers greater than
1with no divisors other than1and itself.
Example 1
Input
left = 10, right = 19
Output
[11,13]
Explanation
The primes in range are 11, 13, 17, and 19. The smallest difference is 2, achieved by (11, 13).
Example 2
Input
left = 14, right = 16
Output
[-1,-1]
Explanation
There are no prime numbers in the range, so no pair can be formed.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.