Closest Prime Numbers in Range Problem
#2523
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2523.
Given two positive integers left and right, find the two integers num1 and num2 such that:
left <= num1 < num2 <= right.- Both
num1andnum2are prime numbers. num2 - num1is the minimum amongst all other pairs satisfying the above conditions.
Return the positive integer array ans = [num1, num2]. If there are multiple pairs satisfying these conditions, return the one with the smallest num1 value. If no such numbers exist, return [-1, -1].
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.
Constraints:
1 <= left <= right <= 10^6
Solution
Approach: Linear Sieve
Run a linear sieve up to right to list all primes, keep the ones inside [left, right], and scan neighbouring pairs for the smallest gap. Because the primes are visited in increasing order, using a strict < returns the pair with the smallest first element on ties. If fewer than two primes lie in the range, the answer is [-1, -1].
Complexity: O(right) time and O(right) space.
class Solution:
def closestPrimes(self, left: int, right: int) -> List[int]:
cnt = 0
st = [False] * (right + 1)
prime = [0] * (right + 1)
for i in range(2, right + 1):
if not st[i]:
prime[cnt] = i
cnt += 1
j = 0
while prime[j] <= right // i:
st[prime[j] * i] = 1
if i % prime[j] == 0:
break
j += 1
p = [v for v in prime[:cnt] if left <= v <= right]
mi = float('inf')
ans = [-1, -1]
for a, b in zip(p, p[1:]):
if b - a < mi:
mi = b - a
ans = [a, b]
return ans