Leetcode #2523: Closest Prime Numbers in Range
In this guide, we solve Leetcode #2523 Closest Prime Numbers in Range in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given two positive integers left and right, find the two integers num1 and num2 such that: left <= num1 < num2 <= right . Both num1 and num2 are prime numbers.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math, Number Theory
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
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.
Python Solution
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 = inf
ans = [-1, -1]
for a, b in pairwise(p):
if (d := b - a) < mi:
mi = d
ans = [a, b]
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.