Closest Prime Numbers in Range

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

  • left <= num1 < num2 <= right.
  • Both num1 and num2 are 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 smallest num1 value. If no such numbers exist, return [-1, -1].

Example 1
Inputleft = 10, right = 19
Output[11,13]
The prime numbers between 10 and 19 are 11, 13, 17, and 19; the closest gap is 2, achieved by [11, 13] and [17, 19], so [11, 13] is returned because 11 is smaller.
Example 2
Inputleft = 4, right = 6
Output[-1,-1]
There exists only one prime number in the given range, so the conditions cannot be satisfied.

Constraints

  • 1 <= left <= right <= 10^6

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate