Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[].
Method 2
1) Traverse array from left side and stop if either x or y are found. Store index of this first occurrrence in a variable say prev
2) Now traverse arr[] after the index prev. If the element at current index i matches with either x or y then check if it is different from arr[prev]. If it is different then update the minimum distance if needed. If it is same then update prev i.e., make prev = i.
Read full article from Find the minimum distance between two numbers | GeeksforGeeks
Method 2
1) Traverse array from left side and stop if either x or y are found. Store index of this first occurrrence in a variable say prev
2) Now traverse arr[] after the index prev. If the element at current index i matches with either x or y then check if it is different from arr[prev]. If it is different then update the minimum distance if needed. If it is same then update prev i.e., make prev = i.
int minDist(int arr[], int n, int x, int y){ int i = 0; int min_dist = INT_MAX; int prev; // Find the first occurence of any of the two numbers (x or y) // and store the index of this occurence in prev for (i = 0; i < n; i++) { if (arr[i] == x || arr[i] == y) { prev = i; break; } } // Traverse after the first occurence for ( ; i < n; i++) { if (arr[i] == x || arr[i] == y) { // If the current element matches with any of the two then // check if current element and prev element are different // Also check if this value is smaller than minimm distance so far if ( arr[prev] != arr[i] && (i - prev) < min_dist ) { min_dist = i - prev; prev = i; } else prev = i; } } return min_dist;}