# Hackerrank Minimum Distance Solution

In this article, you can find the solution for the Hackerrank “Minimum Distance” challenge. The following section contains the description of the challenge provided by the Hackerrank website:

The distance between two array values is the number of indices between them. Given a, find the minimum distance between any pair of equal elements in the array. If no such value exists, return -1.

Let’s make it more clear using an example. An array just like the one in the below image will be given in the input and we want to find the minimum distance between the same values.

As you can see in the image the minimum distance belongs to number 4 with value 3 which will be returned in the out put.

# Solution

There are a lot of different approaches to solving this problem. but one of the easiest is as follow:

`public static int minimumDistances(List<Integer> a) {    int result = -1 ;    for( int i = 0 ; i<a.size() ; i++){        for( int j = i+1 ; j<a.size() ; j++){            int distance = -1;            if( a.get(i).equals(a.get(j)) ){                distance = j - i;                if (distance < result || result == -1 ) result = distance;                break;            }        }    }    return result;}`

The code will go through the items one by one and will check if any equal element exists in the list. After that will store the distance and override if any distance was shorter than the one that has been stored before.

We do recommend that before just using the code try to solve the issue yourself and try this checking this solution in case you have failed to pass all the tests.

Hope this article helped you and please support me by your applaud for the story. if you don’t know how it is just like this:

Or buy me a coffee here!

--

--