Skip to content

Commit 186c3d3

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 2523
1 parent ad8ba7d commit 186c3d3

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@
262262
- [1964 Find the Longest Valid Obstacle Course at Each Position](https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/description/)
263263
- [2140 Solving Questions With Brainpower](https://leetcode.com/problems/solving-questions-with-brainpower/description/)
264264
- [2466 Count Ways To Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings/description/)
265+
- [2523 Closest Prime Numbers in Range](https://leetcode.com/problems/closest-prime-numbers-in-range/description/)
265266
- [2799 Count Complete Subarrays in an Array](https://leetcode.com/problems/count-complete-subarrays-in-an-array/description/)
266267
- [3392 Count Subarrays of Length Three With a Condition](https://leetcode.com/problems/count-subarrays-of-length-three-with-a-condition/description/)
267268

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def getPrimes(self, left: int, right: int) -> List[int]:
8+
primes = [True for i in range(right + 1)]
9+
primes[0] = primes[1] = False
10+
p = 2
11+
while p * p < right + 1:
12+
if primes[p]:
13+
for i in range(p * p, right + 1, p):
14+
primes[i] = False
15+
p += 1
16+
return [i for i in range(left, right + 1) if primes[i]]
17+
18+
def closestPrimes(self, left: int, right: int) -> List[int]:
19+
primes = self.getPrimes(left, right)
20+
21+
if len(primes) < 2:
22+
return [-1, -1]
23+
if len(primes) == 2:
24+
return primes
25+
26+
prime1 = primes[0]
27+
prime2 = primes[1]
28+
for i in range(0, len(primes) - 1):
29+
if primes[i + 1] - primes[i] < prime2 - prime1:
30+
prime1 = primes[i]
31+
prime2 = primes[i + 1]
32+
return [prime1, prime2]
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._2523_closest_prime_numbers_in_range import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["left", "right", "expected"],
10+
argvalues=[
11+
(10, 19, [11, 13]),
12+
(4, 6, [-1, -1]),
13+
(19, 31, [29, 31]),
14+
],
15+
)
16+
def test_func(left: int, right: int, expected: List[int]):
17+
"""Tests the solution of a LeetCode problem."""
18+
closest_primes = Solution().closestPrimes(left, right)
19+
assert closest_primes == expected

0 commit comments

Comments
 (0)