Minimum Distances

Parag Naik
2 min readApr 7, 2021


Problem:-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.

Photo by Marek Piwnicki on Unsplash

A very straight forward and easy hackerrank problem, in which we have to find the distance between multiple matching pair and return the minimum among them. Lets move towards the code.

def minimumDistances(a):
for i in range(len(a)):
for j in range(i+1,len(a)):
if a[i]==a[j]:
if len(lst)==0:
return -1
return min(lst)

Here we will first declare an empty list in which we will insert the distance between two matching pair. We will use two for loop ,the first for loop we run till the end of the list “a” and second will start at i+1.we will check if the element has a matching pair inside the list ,if so we will find the distance between them (index) and then append it in the list lst.Then in the next if condition we will find the minimum among the distance inserted in the list lst.if no matching pair is found we will return -1.

“If God closes a door and a window, consider the fact that it might be time to build a whole new house”. I have seen multiple doors and windows shot down in my life hope this door is a way to my new world. Keep working and keep hustling….(Cheer:-PN).



Parag Naik