Closest Prime Numbers in Range — LeetCode 2523 Python Solution

MediumMathNumber Theory
Problem
#2523
Reading time
4 min

The problem

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.

Example

Input
left = 10, right = 19
Output
[11,13]
Explanation
The prime numbers between 10 and 19 are 11, 13, 17, and 19.

Python solution

Python
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

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2523. Closest Prime Numbers in Range is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2523. Closest Prime Numbers in Range?
LeetCode 2523. Closest Prime Numbers in Range is rated Medium on LeetCode.
What is the time complexity of LeetCode 2523. Closest Prime Numbers in Range?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2523. Closest Prime Numbers in Range?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2523. Closest Prime Numbers in Range cover?
LeetCode 2523. Closest Prime Numbers in Range is tagged Math and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview