- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 41 lines of Java from the credited upstream file 2523.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] closestPrimes(int left, int right) {3 final boolean[] isPrime = sieveEratosthenes(right + 1);4 List<Integer> primes = new ArrayList<>();5 6 for (int i = left; i <= right; ++i)7 if (isPrime[i])8 primes.add(i);9 10 if (primes.size() < 2)11 return new int[] {-1, -1};12 13 int minDiff = Integer.MAX_VALUE;14 int num1 = -1;15 int num2 = -1;16 17 for (int i = 1; i < primes.size(); ++i) {18 final int diff = prime.get(i) - prime.get(i - 1);19 if (diff < minDiff) {20 minDiff = diff;21 num1 = prime.get(i - 1);22 num2 = prime.get(i);23 }24 }25 26 return new int[] {num1, num2};27 }28 29 private boolean[] sieveEratosthenes(int n) {30 boolean[] isPrime = new boolean[n];31 Arrays.fill(isPrime, true);32 isPrime[0] = false;33 isPrime[1] = false;34 for (int i = 2; i * i < n; ++i)35 if (isPrime[i])36 for (int j = i * i; j < n; j += i)37 isPrime[j] = false;38 return isPrime;39 }40}41