Skip to main content
Back to problems
Leetcode
Medium
Number Theory
Math
Arrays
Closest Prime Numbers In Range

Find the pair of prime numbers within a given interval whose difference is smallest.

Acceptance 0%
Problem Statement

Closest Prime Numbers in Range

Given two integers left and right, consider all prime numbers in the inclusive range [left, right].

Return the pair of primes with the smallest absolute difference. If there are multiple pairs with the same minimum difference, return the pair with the smaller first prime.

If fewer than two prime numbers exist in the range, return [-1, -1].

A number is prime if it has exactly two positive divisors: 1 and itself.

Input Format

  • Two integers left and right describing an inclusive range.
  • You may assume left <= right.

Output Format

  • Return two integers representing the closest pair of primes in the range.
  • If no valid pair exists, return [-1, -1].

Constraints

  • 1 <= left <= right
  • The range may be large enough that checking each number naively is inefficient.
  • Prime numbers are integers greater than 1 with no divisors other than 1 and itself.
Examples
Sample cases returned by the problem API.

Example 1

Input

left = 10, right = 19

Output

[11,13]

Explanation

The primes in range are 11, 13, 17, and 19. The smallest difference is 2, achieved by (11, 13).

Example 2

Input

left = 14, right = 16

Output

[-1,-1]

Explanation

There are no prime numbers in the range, so no pair can be formed.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.