DEV Community

Phoenix
Phoenix

Posted on

Minimum distance in an Array

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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay