Skip to main content

Closest Prime Numbers in Range - Solution & Explanation

MediumMathNumber Theory19 min readAsked at: Amazon, Microsoft, Meta +3
Practice this problem

Problem Statement

Given two positive integers left and right, find the two integers num1 and num2 such that:

  • left <= num1 < num2 <= right .
  • num1 and num2 are both 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 minimum num1 value or [-1, -1] if such numbers do not exist.

A number greater than 1 is called prime if it is only divisible by 1 and itself.

 

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

 

Approach Overview

Problem Overview: You are given two integers left and right. The task is to find two prime numbers within this inclusive range whose difference is the smallest among all prime pairs in the range. If fewer than two primes exist, return [-1, -1].

Approach 1: Direct Prime Check with Iteration (Time: O((R-L) * sqrt(R)), Space: O(1))

Iterate through every number from left to right and check whether it is prime. A number is prime if it has no divisors from 2 to sqrt(n). Keep track of the previous prime encountered and compute the difference with the current prime. Update the best pair whenever you find a smaller gap. This approach relies purely on arithmetic checks and constant memory, making it simple to implement when the range size is small. It directly uses concepts from math and number theory.

Approach 2: Sieve of Eratosthenes Optimization (Time: O(n log log n), Space: O(n))

Generate all prime numbers up to right using the Sieve of Eratosthenes. Create a boolean array where each index represents whether the number is prime. Start with all numbers marked prime, then mark multiples of each prime starting from 2. After building the sieve, iterate from left to right and collect primes or compare them on the fly. Track the previous prime and update the smallest difference pair. This avoids repeated square root checks and is significantly faster for large ranges.

Recommended for interviews: Start with the direct prime check to demonstrate understanding of primality testing. Interviewers usually expect the optimized approach using the sieve when the range becomes large. The sieve shows familiarity with classic number theory techniques and reduces repeated work, making it the practical solution for competitive programming and system constraints.

Approach 1: Direct Prime Check with Iteration

This approach involves iterating through each number in the given range and checking if it is a prime number by testing divisibility from 2 up to the square root of the number. After identifying prime numbers, the algorithm tracks the pair with the minimum difference.

This C solution uses a helper function is_prime to check if a number is prime. It loops over each number in the range and records the closest prime pair.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n*sqrt(m)) where n is the range size and m is the number being checked for primality.
Space Complexity: O(1)

Try this approach in the editor →

Approach 2: Sieve of Eratosthenes Optimization

This approach leverages the Sieve of Eratosthenes, a well-known algorithm for finding all prime numbers up to a given limit. It marks non-prime numbers in a boolean array, making subsequent queries to check if a number is prime efficient. After sieving up to the right range boundary, the solution checks the range and identifies the closest prime numbers.

This C solution incorporates the Sieve of Eratosthenes to preprocess primes up to the right boundary, then checks the range for the closest prime pair.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log log n) for sieving, plus O(d) for checking range where d is the difference between left and right.
Space Complexity: O(n) for storing prime markers.

Try this approach in the editor →

Approach 3: Linear Sieve

For the given range [left, right], we can use the linear sieve method to find all prime numbers. Then, we traverse the prime numbers in ascending order to find the pair of adjacent prime numbers with the smallest difference, which will be the answer.

The time complexity is O(n), and the space complexity is O(n). Here, n = right.

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Direct Prime Check with Iteration

Time Complexity: O(n*sqrt(m)) where n is the range size and m is the number being checked for primality.
Space Complexity: O(1)

Sieve of Eratosthenes Optimization

Time Complexity: O(n log log n) for sieving, plus O(d) for checking range where d is the difference between left and right.
Space Complexity: O(n) for storing prime markers.

Linear Sieve—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Direct Prime Check with IterationO((R-L) * sqrt(R))O(1)Small ranges or when avoiding extra memory
Sieve of EratosthenesO(n log log n)O(n)Large ranges where repeated prime checks are expensive

Video Solution

Closest Prime Numbers in Range - Leetcode 2523 - Python • NeetCodeIO • 9,398 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Closest Prime Numbers in Range easy or hard?
Closest Prime Numbers in Range is typically classified as a Medium problem. The logic is straightforward once you recognize that generating primes efficiently with the Sieve of Eratosthenes avoids repeated expensive primality checks.
Closest Prime Numbers in Range Python/Java solution
Both Python and Java implementations follow the same logic: either check primality for each number using a sqrt loop or build a sieve array up to the upper bound. After identifying primes, maintain the previous prime and update the pair with the smallest difference.
How to solve Closest Prime Numbers in Range in O(n)?
An O(n) style scan is achieved after preprocessing primes with the Sieve of Eratosthenes. Build the sieve up to the maximum value, then iterate through the range once while keeping track of the previous prime and updating the smallest difference pair.
What is the best approach for Closest Prime Numbers in Range?
The most efficient approach is using the Sieve of Eratosthenes to precompute all primes up to the upper bound of the range. After generating primes, scan from left to right and track the pair with the smallest difference. This runs in O(n log log n) time and avoids repeated primality checks.
Is Closest Prime Numbers in Range asked at Google/Amazon/Meta?
Prime number and number theory problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involving prime generation, sieve techniques, or range-based prime queries are common in coding interviews and competitive programming.
What data structure is used in Closest Prime Numbers in Range?
The optimized solution uses a boolean array (or bitset) to represent whether each number is prime in the Sieve of Eratosthenes. The algorithm also tracks the previous prime value while iterating through the range to compute differences.
What is the time complexity of Closest Prime Numbers in Range?
The direct iteration approach checks each number for primality in O(sqrt(n)), giving roughly O((R-L) * sqrt(R)) time. Using the Sieve of Eratosthenes reduces the complexity to O(n log log n) for preprocessing plus O(n) scanning, which is typically faster for large ranges.

Ready to solve this problem?

Practice Closest Prime Numbers in Range with our built-in code editor and test cases.

Practice on FleetCode