Last active
February 22, 2021 08:28
-
-
Save samarthsewlani/b4f606bf247982ee8d99771af1e818f1 to your computer and use it in GitHub Desktop.
Minimum Distances HackerRank Solution ( Better Logic )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def minimumDistances(a): | |
n=len(a) | |
minimum=n+1 #Initializing with n+1 because if no updates take place we should return -1 as there are no matching pairs | |
# Note:- If any matching pairs is found the distance would be less than n | |
indexes=dict() #Creating an empty dictionary | |
for i in range(n): | |
if a[i] in indexes: #If elem is present, append its index in its list | |
indexes[a[i]].append(i) | |
else: #If elem is not present,initialize it by a list with t's index | |
indexes[a[i]]=[i] | |
for i in indexes: #For every element in the dictionary | |
length=len(indexes[i]) | |
if n>1: #We only have to traverse if there are more than 1 element | |
for j in range(1,length): #Traverse & check the distance between two indexes | |
if indexes[i][j]-indexes[i][j-1] < minimum: #Update if required | |
minimum=indexes[i][j]-indexes[i][j-1] | |
if minimum==n+1: #If no matching elements return -1 | |
return -1 | |
return minimum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment