#2523
Closest Prime Numbers in Range
specialist · 850 · lc medium +31 · verified · 51.7% accepted · 923 likes · top 41%
Description
Given integers left and right, find two primes num1 < num2 within [left, right] with the smallest difference. If multiple pairs share the same minimum difference, pick the one with the smaller num1. Return [num1, num2], or [-1, -1] if fewer than two primes exist in the range.
Example 1:
Input: left = 10, right = 19
Output: [11,13]
Explanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19.
The closest gap between any pair is 2, which can be achieved by [11,13] or [17,19].
Since 11 is smaller than 17, we return the first pair.
Example 2:
Input: left = 4, right = 6
Output: [-1,-1]
Explanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.
Code
1
2
3