šŸ” Finding the Closest Prime Numbers in a Range using the Sieve of Eratosthenes (leetcode - 2523)

šŸ” Finding the Closest Prime Numbers in a Range using the Sieve of Eratosthenes

Prime numbers play a crucial role in number theory and various computational applications. In this blog, we will explore an optimized approach to finding the two closest prime numbers within a given range using the Sieve of Eratosthenes. šŸš€

šŸ“Œ Problem Statement

Given two integers left and right, find the two prime numbers within the range [left, right] that have the smallest difference. If there are fewer than two prime numbers, return [-1, -1].

šŸ› ️ Approach

To efficiently solve this problem, we use the Sieve of Eratosthenes algorithm to precompute prime numbers up to right. Then, we extract the prime numbers from the given range and find the closest pair.

✅ Steps to Solve

  1. Initialize a boolean list primes where primes[i] = True indicates i is prime.
  2. Mark 0 and 1 as False (not prime).
  3. Use the Sieve of Eratosthenes to eliminate non-prime numbers.
  4. Extract prime numbers from the given range [left, right].
  5. Iterate through the primes to find the pair with the smallest difference.
  6. Return the closest prime pair or [-1, -1] if there are fewer than two primes.

šŸ“œ Code Implementation


from typing import List

class Solution:
    def closestPrimes(self, left: int, right: int) -> List[int]:
        # Sieve of Eratosthenes
        primes = [True] * (right + 1)
        primes[0], primes[1] = False, False
        for i in range(2, int(right * 0.5) + 1):
            if primes[i]:
                for j in range(i * i, right + 1, i):
                    primes[j] = False
        
        # find primes from the given range
        primes_range = [i for i in range(left, right + 1) if primes[i]]
        # length of prime numbers
        n = len(primes_range)
        closest_pair = [-1, -1]
        # check the length
        if n < 2:
            return closest_pair
        # maximum value
        min_dif = float('inf')
        # checking for minimum difference
        for i in range(n - 1):
            dif = primes_range[i + 1] - primes_range[i]
            if dif < min_dif:
                min_dif = dif
                closest_pair = [primes_range[i], primes_range[i + 1]]
        # return the final value
        return closest_pair
    

⏳ Complexity Analysis

  • Sieve of Eratosthenes: O(N log log N)
  • Extracting primes in the range: O(N)
  • Finding the closest pair: O(K) (where K is the number of primes in range)
  • Overall Complexity: O(N log log N)

šŸ“Š Example Walkthrough

Input:

left = 10, right = 50

Output:

[11, 13]

Explanation:

Primes in range [10, 50]: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]. The closest pair is (11, 13) with a difference of 2.

šŸš€ Conclusion

The Sieve of Eratosthenes provides an efficient way to compute prime numbers, making this approach optimal for large values of right. By leveraging this algorithm, we can quickly find the closest prime numbers in a given range.

Hope you found this useful! Happy coding! šŸŽÆ

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

14. Longest Common Prefix