[LeetCode] 2523. Closest Prime Numbers in Range (Python)

2025. 3. 7. 18:29·알고리즘/LeetCode

 

 

난이도: Medium

Problem Description


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.
  • num2 - num1 is the minimum amongst all other pairs satisfying the above conditions.

Return the positive integer array ans = [num1, num2]. If there are multiple pairs satisfying these conditions, return the one with the smallest num1 value. If no such numbers exist, return [-1, -1].

 

Problem Example


Example 1:

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.

Example 2:

Input: left = 4, right = 6
Output: [-1,-1]
Explanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.

 

Constraints


  • 1 <= left <= right <= 106

 

✏️ Solution


class Solution:
    def closestPrimes(self, left: int, right: int) -> List[int]:
        def make_prime_num(left, n):
            prime = [True] * (n+1)
            prime[0] = False
            if n > 0:
                prime[1] = False
            for i in range(2, int(math.sqrt(n)) + 1):
                if prime[i]:
                    j=2
                    for j in range(i * i, n + 1, i):
                        prime[j] = False

            return [i for i in range(left, right + 1) if prime[i]]

        prime = make_prime_num(left, right)
        print(prime)
        if len(prime) < 2:
            return [-1, -1]
        
        answer = [left-1, right+1]
        for i in range(len(prime)-1):
            if prime[i+1] - prime[i] < answer[1] - answer[0]:
                answer[0] = prime[i]
                answer[1] = prime[i+1] 

        return answer

 

에라토스테네스의 체를 사용하여 문제를 해결했다.

 

먼저 1부터 right까지의 수에서 소수를 찾아 left와 right 사이에 존재하는 소수를 따로 저장했다.

예를 들어 left = 10, right  = 19이면 [11, 13, 17, 19]로 저장된다.

 

이 때 left와 right 사이에 존재하는 소수의 수가 없거나 1개라면 [-1, -1]을 return 하였다.

 

소수의 수가 2개 이상이라면 현재 요소와 다음 요소의 차를 구해 answer[1] - answer[0]과 비교하여 answer 값들을 업데이트 해나갔다.

 

예를 들어 left = 10, right = 19이면 [11, 13, 17, 19]를 얻을 수 있다.

처음에 answer를 =[left-1, right+1] 즉 [9, 20]으로 설정한다.

 

모든 소수 요소에 대해 다음 요소와 차를 구한다.

현재 요소가 11일 때 다음 요소는 13이다.

13-11 = `2` < 20 - 9 = `11`이기 때문에 answer[0]과 answer[1]에 11과 13을 저장한다.

 

다음으로 넘어가 13과 17에 대해 차이를 구하고 answer의 요소의 차이와 비교하면 17 - 13 = `5` > 13 - 11 = `2`이기 때문에 넘어간다.

 

다음으로 넘어가 17과 19에 대해 차이를 구하고 answer의 요소의 차이와 비교하면 19-17 = '2' = 13-11='2'로 같다.

 

하지만 문제에서 답이 여러개이면 answer[0]의 요소가 더 작은 것을 구하라고 했다. 따라서, 17 > 11이기 때문에 넘어간다.

19 다음의 요소는 없기 때문에 반복문을 종료한다.

 

마지막으로 이러한 answer를 return 하여 정답을 맞을 수 있었다.

 

⚙️ Runtime & Memory


 

성능이 다른 사람들에 비해 낮긴 하다..

 


문제: 2523. Closest Prime Numbers in Range

 

깃허브: github

 

algorithmPractice/LeetCode/2610-closest-prime-numbers-in-range at main · laewonJeong/algorithmPractice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com

 

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 3208. Alternating Groups II (Python)  (0) 2025.03.09
[LeetCode] 2379. Minimum Recolors to Get K Consecutive Black Blocks (Python)  (1) 2025.03.08
[LeetCode] 2965. Find Missing and Repeated Values (Python)  (0) 2025.03.06
[LeetCode] 2579. Count Total Number of Colored Cells (Python)  (0) 2025.03.05
[LeetCode] 1780. Check if Number is a Sum of Powers of Three (Python)  (0) 2025.03.04
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 3208. Alternating Groups II (Python)
  • [LeetCode] 2379. Minimum Recolors to Get K Consecutive Black Blocks (Python)
  • [LeetCode] 2965. Find Missing and Repeated Values (Python)
  • [LeetCode] 2579. Count Total Number of Colored Cells (Python)
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    백트래킹
    누적합
    도커
    프로그래머스
    docker
    Python
    BFS
    코딩테스트
    분산처리
    아파치 하둡
    programmers
    쿠버네티스
    String
    알고리즘
    분산
    dfs
    heapq
    아파치 스파크
    문자열
    이진탐색
    DP
    leetcode
    그래프
    Apache Spark
    티스토리챌린지
    오블완
    Kubernetes
    파이썬
    우선순위큐
    리트코드
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2523. Closest Prime Numbers in Range (Python)
상단으로

티스토리툴바