Use two loops: The outer loop iterates through each element of arr[] one at a time. The inner loop iterates over each element after the one selected by the outer loop. If the elements chosen by the outer and inner loops match the values of x or y, update the minimum distance if necessary.
publicclassSolution {
publicintminDistance(int[] arr, int x, int y) {
int n = arr.length; // Get the length of the arrayint minDist = Integer.MAX_VALUE; // Initialize minimum distance with a large value// Outer loop to pick every element one by onefor (int i = 0; i < n; i++) {
// Inner loop to pick every element after element picked by outer// loopfor (int j = i + 1; j < n; j++) {
// Check if the pair (arr[i], arr[j]) is what we wantif ((arr[i]== x && arr[j]== y)
|| (arr[i]== y && arr[j]== x)) {
// Calculate the distance between the current pairint dist = Math.abs(i - j);
// Update minDist if the current distance is smallerif (dist < minDist) {
minDist = dist;
}
}
}
}
// If no valid distance is found, return -1if (minDist == Integer.MAX_VALUE) {
return-1;
}
return minDist; // Return the minimum distance }
publicstaticvoidmain(String[] args) {
Solution solution =new Solution();
int[] arr = {3, 5, 4, 2, 6, 5, 6, 8, 3};
int x = 3;
int y = 6;
int result = solution.minDistance(arr, x, y);
System.out.println(
"The minimum distance is: "+ result); // Output should be 4 }
}
classSolution:
defminDistance(self, arr: List[int], x: int, y: int) -> int:
n = len(arr)
min_distance = float("inf")
last_pos_x =-1 last_pos_y =-1# Traverse the arrayfor i in range(n):
if arr[i] == x:
last_pos_x = i
# If y has been seen, update the minimum distanceif last_pos_y !=-1:
min_distance = min(
min_distance, abs(last_pos_x - last_pos_y)
)
if arr[i] == y:
last_pos_y = i
# If x has been seen, update the minimum distanceif last_pos_x !=-1:
min_distance = min(
min_distance, abs(last_pos_y - last_pos_x)
)
# If no valid distance is found, return -1return min_distance if min_distance != float("inf") else-1# Example usagesol = Solution()
arr = [3, 5, 4, 2, 6, 5, 6, 8, 3]
x =3y =6result = sol.minDistance(arr, x, y)
print("The minimum distance is:", result) # Output should be 4
⏰ Time complexity: O(n^2), where n is the length of the input array arr.
🧺 Space complexity: O(1)
Method 2 - Keeping the indices of the element occurences#
The algorithm iterates through the array to track the positions of the given elements x and y. It continually updates the minimum distance when both elements have been seen.
Here is the approach:
Initialize Variables: Use variables to keep track of the latest positions of x and y in the array.
Iterate through the Array: Traverse the array to find the positions of the elements x and y.
Update Positions and Minimum Distance: Each time you encounter x or y, update their latest positions and calculate the distance if both elements have been seen.
Return Minimum Distance: Return the minimum distance found between the two elements.
publicclassSolution {
publicintminDistance(int[] arr, int x, int y) {
int n = arr.length;
int minDistance = Integer.MAX_VALUE;
int lastPosX =-1;
int lastPosY =-1;
// Traverse the arrayfor (int i = 0; i < n; i++) {
if (arr[i]== x) {
lastPosX = i;
// If y has been seen, update the minimum distanceif (lastPosY !=-1) {
minDistance = Math.min(minDistance, Math.abs(lastPosX - lastPosY));
}
}
if (arr[i]== y) {
lastPosY = i;
// If x has been seen, update the minimum distanceif (lastPosX !=-1) {
minDistance = Math.min(minDistance, Math.abs(lastPosY - lastPosX));
}
}
}
// If no valid distance is found, return -1if (minDistance == Integer.MAX_VALUE) {
return-1;
}
return minDistance;
}
publicstaticvoidmain(String[] args) {
Solution solution =new Solution();
int[] arr = {3, 5, 4, 2, 6, 5, 6, 8, 3};
int x = 3;
int y = 6;
int result = solution.minDistance(arr, x, y);
System.out.println(
"The minimum distance is: "+ result); // Output should be 4 }
}
classSolution:
defminDistance(self, arr: List[int], x: int, y: int) -> int:
n = len(arr)
min_distance = float("inf")
last_pos_x =-1 last_pos_y =-1# Traverse the arrayfor i in range(n):
if arr[i] == x:
last_pos_x = i
# If y has been seen, update the minimum distanceif last_pos_y !=-1:
min_distance = min(
min_distance, abs(last_pos_x - last_pos_y)
)
if arr[i] == y:
last_pos_y = i
# If x has been seen, update the minimum distanceif last_pos_x !=-1:
min_distance = min(
min_distance, abs(last_pos_y - last_pos_x)
)
# If no valid distance is found, return -1return min_distance if min_distance != float("inf") else-1# Example usagesol = Solution()
arr = [3, 5, 4, 2, 6, 5, 6, 8, 3]
x =3y =6result = sol.minDistance(arr, x, y)
print("The minimum distance is:", result) # Output should be 4