Sort by

recency

|

1391 Discussions

|

  • + 0 comments

    Python Here is the magic

    def minimumDistances(a):
        d = {key:abs(a.index(key) - (len(a)-1-a[::-1].index(key))) for key in set(a) if a.count(key)>1}
        val = min(d.values()) if len(d)>0 else -1
        return val
    
  • + 0 comments

    Way to do it with out nested for loops

    def minimumDistances(a):
        # Write your code here
        values = []
        for i in a:
            start = a.index(i)
            if a.count(i) >= 2:
                #d=a.index(i, start+1)
                values.append(abs(a.index(i, start+1)-start))
                print(i)
        if values:
            return min(values)
        else:
            return -1
    
  • + 1 comment

    JavaScript solution:

    function minimumDistances(a) {
        let minimumDistance = a.length;
        for (let i = 0; i < a.length; i++) {
            const currentNumber = a[i];
            const nextNumberIndex = a.indexOf(currentNumber, i + 1);
            if (nextNumberIndex !== -1) {
                const indicesBetween = nextNumberIndex - i;
                if (minimumDistance > indicesBetween) {
                    minimumDistance = indicesBetween;
                }
            }
        }
        if (minimumDistance === a.length) {
            return -1;
        }
        return minimumDistance;
    }
    
  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/H8aBskFE2XI

    int minimumDistances(vector<int> a) {
        map<int, int>mp;
        int result = 1000;
        for(int i = 0; i < a.size(); i++){
            if(mp[a[i]]){
                result = min(result, i + 1 - mp[a[i]]);
            }
            mp[a[i]] = i+1;
        }
        return (result == 1000) ? -1:result;
    }
    
  • + 0 comments
    def minimumDistances(arr):
        dct={}
        for i in range(len(a)):
            if arr[i] in dct:
                dct[arr[i]].append(i)
            else:
                dct[arr[i]]=[i]
        ans=[]
        #print(dct)
        for lis in dct:
            if len(dct[lis])>1:
                ans.append(abs(dct[lis][0]-dct[lis][1]))
        #print(ans)
        if ans == []:
            return '-1'
        return min(ans)