Hackerrank - Minimum Distances Solution
1 min read

Hackerrank - Minimum Distances Solution

Hackerrank - Minimum Distances Solution

We define the distance between two array values as the number of indices between the two values. Given , find the minimum distance between any pair of equal elements in the array. If no such value exists, print .

For example, if , there are two matching pairs of values: . The indices of the 's are  and , so their distance is . The indices of the 's are  and , so their distance is .

Function Description

Complete the minimumDistances function in the editor below. It should return the minimum distance between any two matching elements.

minimumDistances has the following parameter(s):

  • a: an array of integers

Input Format

The first line contains an integer , the size of array .
The second line contains  space-separated integers .


Output Format

Print a single integer denoting the minimum  in . If no such value exists, print .

Sample Input

7 1 3 4 1 7

Sample Output


Here, we have two options:

  • and  are both , so .
  • and  are both , so .

The answer is .

Solution in Python

from collections import defaultdict

def minimumDistances(a):
    d = defaultdict(list)
    for k,v in enumerate(a):
    md = 0
    for v in d.values():
        if not len(v)>1:
        if not md:
            md = v[1]-v[0]
        for i in range(len(v)-1):
            dif = v[i+1]-v[i]
            if dif<md:
                md = dif
    return md or -1

n = int(input())
a = list(map(int,input().split()))

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.