public final class ArrayDistance {
private ArrayDistance() {
// Prevent instantiation of utility class.
}
/**
* Finds the minimum distance between two target values in an array.
*
* Example:
* array = {2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3}
* target1 = 3
* target2 = 8
*
* Result: 2
*
* @param array input array
* @param target1 first target value
* @param target2 second target value
* @return minimum distance between target1 and target2,
* or -1 if no valid pair exists
* @throws IllegalArgumentException if array is null
*/
public static int findMinimumDistance(
int[] array,
int target1,
int target2) {
if (array == null) {
throw new IllegalArgumentException("Array cannot be null.");
}
int lastSeenIndex = -1;
int minDistance = Integer.MAX_VALUE;
for (int currentIndex = 0; currentIndex < array.length; currentIndex++) {
int currentValue = array[currentIndex];
// Skip values that are not relevant.
if (currentValue != target1 && currentValue != target2) {
continue;
}
/**
* If we've already seen one of the target values and
* the current value is the other target value,
* update the minimum distance.
*/
if (lastSeenIndex != -1 && currentValue != array[lastSeenIndex]) {
minDistance = Math.min(
minDistance,
currentIndex - lastSeenIndex);
}
// Record the most recent occurrence.
lastSeenIndex = currentIndex;
}
return minDistance == Integer.MAX_VALUE
? -1
: minDistance;
}
public static void main(String[] args) {
int[] array = {2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3};
int result = findMinimumDistance(array, 3, 8);
if (result >= 0) {
System.out.println("Minimum distance between 3 and 8: " + result);
} else {
System.out.println("No valid pair found.");
}
}
}
/*
run:
Minimum distance between 3 and 8: 2
*/