The Closest Prime Numbers in Range interview question asks you to find two prime numbers within a given closed interval [left, right] such that their absolute difference is minimized. If there are multiple pairs with the same minimum difference, you should return the pair with the smallest left value. If fewer than two prime numbers exist in the range, you return [-1, -1].
Companies like Microsoft and Google ask the Closest Prime Numbers in Range coding problem to test your knowledge of Number Theory and efficient searching. Generating prime numbers efficiently is a fundamental computer science task. This problem specifically evaluates whether you can use a sieve method (like Sieve of Eratosthenes) to handle large ranges without exceeding time or memory limits.
The most efficient Math interview pattern for this problem is the Sieve of Eratosthenes. Instead of checking each number for primality individually (which is slow for large ranges), you create a boolean array up to right and mark non-primes. Once you have the list of primes between left and right, finding the "closest" pair is a simple linear scan through the sorted primes.
Range: [10, 20]
2, 3, 5, 7, 11, 13, 17, 19.>= 10: 11, 13, 17, 19.|13 - 11| = 2|17 - 13| = 4|19 - 17| = 2[11, 13] and [17, 19] have a difference of 2.[11, 13].1 is not a prime number.Always remember that the Sieve of Eratosthenes takes O(N log log N) time, which is nearly linear. It is almost always the preferred way to find multiple primes in a range.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Prime Palindrome | Medium | Solve | |
| The kth Factor of n | Medium | Solve | |
| Smallest Even Multiple | Easy | Solve | |
| Check if Point Is Reachable | Hard | Solve | |
| Insert Greatest Common Divisors in Linked List | Medium | Solve |