Leetcode 2523: Closest Prime Numbers in Range

grid47
grid47
Exploring patterns and algorithms
Feb 28, 2024 6 min read

Given two integers left and right, find the two prime numbers num1 and num2 such that: left <= num1 < num2 <= right, both are prime numbers, and the difference num2 - num1 is the smallest among all valid pairs. If multiple pairs have the same smallest difference, return the pair with the smallest num1. If no such pair exists, return [-1, -1].
Problem
Approach
Steps
Complexity
Input: You are given two integers `left` and `right`. Find the pair of prime numbers `num1` and `num2` where `left <= num1 < num2 <= right`.
Example: left = 15, right = 30
Constraints:
• 1 <= left <= right <= 10^6
Output: Return the pair `[num1, num2]` where `num1` and `num2` are prime numbers and the difference `num2 - num1` is the smallest. If no such pair exists, return `[-1, -1]`.
Example: Output: [17, 19]
Constraints:
• The output must be a list of two integers representing the prime numbers, or [-1, -1] if no such pair exists.
Goal: Find the pair of prime numbers `num1` and `num2` such that the difference between them is minimized, while satisfying the constraints.
Steps:
• Generate all prime numbers up to the value of `right` using the Sieve of Eratosthenes.
• Find all prime numbers between `left` and `right`.
• Iterate through the primes to find the pair with the smallest difference.
Goal: The range `[left, right]` is such that `1 <= left <= right <= 10^6`.
Steps:
• The time complexity should be efficient enough to handle input up to 10^6.
Assumptions:
• The input values `left` and `right` are within the given constraints.
Input: left = 15, right = 30
Explanation: The prime numbers between 15 and 30 are [17, 19, 23, 29]. The smallest difference is 2, which occurs between 17 and 19.

Input: left = 50, right = 60
Explanation: The prime numbers between 50 and 60 are [53, 59], with a difference of 6.

Input: left = 8, right = 10
Explanation: There are no prime numbers between 8 and 10, so the output is `[-1, -1]`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus