Closest Prime Numbers in Range — LeetCode 2523 Python Solution
- Problem
- #2523
- Pattern
- Math and Number Theory
- Reading time
- 4 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.