This content originally appeared on DEV Community and was authored by Phoenix
Problem Link - Minimum Distance
You are given an array a, of n elements. Find the minimum index based distance between two distinct elements of the array, x and y. Return -1, if either x or y does not exist in the array.
Examples:
Input: arr[] = {1, 2}, x = 1, y = 2
Output: Minimum distance between 1 and 2 is 1.
Input: arr[] = {3, 4, 5}, x = 3, y = 5
Output: Minimum distance between 3 and 5 is 2.
Input: arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}, x = 3, y = 6
Output: Minimum distance between 3 and 6 is 4.
Input: arr[] = {2, 5, 3, 5, 4, 4, 2, 3}, x = 3, y = 2
Output: Minimum distance between 3 and 2 is 1.
Approach
- Initialize two indices i1 and i2 to -1 to store the most recent indices of x and y found during the traversal of the array.
- Initialize a variable mini to a large value (e.g., INT_MAX) to keep track of the minimum distance.
- Traverse through the array and find the indices of x and y,if both were found then calculate the distance between them and update the mini variable.if again we found the x or y, then calcuate the distance with previously found x or y and update the mini variable.
Code
int minDist(int a[], int n, int x, int y) {
// code here
int mini=INT_MAX;
int i1=-1;
int i2=-1;
for(int i=0;i<n;i++){
if(a[i]==x){
i1=i;
}
else if(a[i]==y){
i2=i;
}
if(i1!=-1&&i2!=-1){
mini=min(mini,abs(i2-i1));
}
}
if(i1==-1 || i2==-1){
return -1;
}
return mini;
}
This content originally appeared on DEV Community and was authored by Phoenix
Phoenix | Sciencx (2024-09-25T19:36:46+00:00) Minimum distance in an Array. Retrieved from https://www.scien.cx/2024/09/25/minimum-distance-in-an-array/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.