Closest Prime Numbers in Range (LeetCode 2523): Solution and Explanation

Medium
Math
Number Theory

Find the two primes in [left, right] with the smallest difference, preferring the smaller first number on ties, or return [-1, -1]. Sieve every number up to right, then compare each prime only with the prime just before it.

Intuition

The closest pair must be two consecutive primes. If some prime sat between num1 and num2, pairing it with either end would give a smaller gap.

So the work splits in two: know which numbers are prime, then walk them in order tracking the previous prime and the best gap seen so far.

Testing each number by trial division costs about sqrt(x) per number. The Sieve of Eratosthenes marks every composite up to right in near-linear time by letting each prime cross out its multiples once.

Approach: Sieve of Eratosthenes plus a consecutive-prime scan

  1. Create a boolean array composite of size right + 1.
  2. For each i from 2 while i * i <= right, if i is not composite, mark i*i, i*i + i, ... up to right as composite.
  3. Walk x from max(left, 2) to right, skipping composite numbers.
  4. If a previous prime exists and x - prev is strictly smaller than the best gap, record [prev, x]. Then set prev = x.
  5. Return the best pair, which stays [-1, -1] when the range holds fewer than two primes.

Step-by-step example

left = 10, right = 19
  1. Sieve up to 19: 2 crosses out 4, 6, 8, ..., 18 and 3 crosses out 9 and 15. 5 * 5 = 25 is past 19, so the sieve stops.
  2. The primes from 10 to 19 are 11, 13, 17 and 19.
  3. 11 is the first prime, so it becomes prev. 13 - 11 = 2 gives the first pair, best = [11, 13].
  4. 17 - 13 = 4 is not smaller. 19 - 17 = 2 ties, and ties keep the earlier pair.
  5. Return [11, 13].

Code: Python, Java, C++

1class Solution:
2    def closestPrimes(self, left: int, right: int) -> List[int]:
3        composite = [False] * (right + 1)
4        for i in range(2, int(right ** 0.5) + 1):
5            if not composite[i]:
6                for j in range(i * i, right + 1, i):
7                    composite[j] = True
8        best = [-1, -1]
9        prev = -1
10        for x in range(max(left, 2), right + 1):
11            if composite[x]:
12                continue
13            if prev != -1 and (best[0] == -1 or x - prev < best[1] - best[0]):
14                best = [prev, x]
15            prev = x
16        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(right log log right)

The sieve crosses out multiples of each prime once, which sums to right times log log right. The scan is linear in the range.

Space

O(right)

One boolean per number up to right.

Other approaches

Trial division per number (time O((right - left) sqrt(right)), space O(1))

Check each x in the range for primality by dividing by every number up to sqrt(x). It needs no big array but costs O((right - left) * sqrt(right)), which is slow for wide ranges.

Stop early on a gap of 2 (time O(right log log right), space O(right))

Apart from [2, 3], no two primes are closer than 2, so the scan can return as soon as it finds a gap of 1 or 2. It does not change the worst case but often finishes the scan early.

Common mistakes

  • Treating 1 as prime. When left is 1, the scan must start at 2.
  • Replacing the best pair on an equal gap, which returns the later pair instead of the one with the smallest num1.
  • Starting the inner sieve loop at 2 * i instead of i * i. It is still correct but does extra work, and i * i can overflow 32-bit ints if written carelessly for large right.

Frequently asked questions

Why only compare consecutive primes?

If a prime p lay strictly between num1 and num2, then p - num1 would be smaller than num2 - num1, so the pair could not be the closest. The closest pair therefore has no prime between them.

Why does the sieve start crossing at i * i?

Any smaller multiple k * i with k < i has a prime factor smaller than i, so it was already crossed out when that smaller prime ran.

When is the answer [-1, -1]?

Whenever the range holds zero or one prime, for example [4, 6], which contains only 5, or [24, 28], which contains none.