# Find the minimum distance between two numbers in C++

C++Server Side ProgrammingProgramming

Suppose we have one unsorted array A, and two numbers x and y. We have to find the minimum distance between x and y in A. The array can also contain duplicate elements. So if the array is A = [2, 5, 3, 5, 4, 4, 2, 3], x = 3 and y = 2, then the minimum distance between 3 and 2 is just 1.

To solve this, we have to follow these steps,

• Traverse the array from left to right and stop if either x or y has found. Then store the index of that position into prev
• Now traverse the array after the index prev, if the element with current index i matches with either x or y, then check if it is different from A[prev], if that is different, then update the min index if needed, if that are different, then update prev as prev := i

## Example

#include<iostream>
using namespace std;
int findMinDistance(int A[], int n, int x, int y) {
int i = 0;
int distance = INT_MAX;
int prev_index;
for (i = 0; i < n; i++) {
if (A[i] == x || A[i] == y) {
prev_index = i;
break;
}
}
while (i < n) {
if (A[i] == x || A[i] == y) {
if ( A[prev_index] != A[i] && (i - prev_index) < distance ){
distance = i - prev_index;
prev_index = i;
} else
prev_index = i;
}
i++;
}
return distance;
}
int main() {
int arr[] = {2, 5, 3, 5, 4, 4, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 3;
int y = 2;
cout << "Minimum distance between " << x << " and " << y << " is: "<< findMinDistance(arr, n, x, y);
}

## Output

Minimum distance between 3 and 2 is: 1
Published on 18-Dec-2019 12:42:56