Minimum distance in an Array

Problem LinkMinimum 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; }
Enter fullscreen mode
Exit fullscreen mode

Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Real world asset (rwa) tokenization services. How to install docker and docker compose on ubuntu 20. State of the art datacenter get a host.