Sort by

recency

|

1386 Discussions

|

  • + 0 comments
    // Optimized using Hahsh map
    // TC: O(n) 
    // SC: O(n)
    
    function minimumDistances(a) {
        let hash = {}; // number to its first index 
        let minDist = Infinity; 
        
        for(let i = 0; i < a.length; i++) {
            if(hash[a[i]] !== undefined) {
                minDist = Math.min(minDist, Math.abs(i - hash[a[i]])); 
            }
            else {
                hash[a[i]] = i; 
            }
        }
        
        if(minDist === Infinity) {
            return -1;
        }
        
        return minDist; 
    }
    
  • + 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

    here is my solution

     unordered_map<int, pair<int,int>> NumberToIdx;
        int MinDist = INT_MAX;
    
        for(int i = 0 ; i < a.size(); ++i){
            
            if(NumberToIdx.find(a[i]) == NumberToIdx.end()){
                NumberToIdx[a[i]] = make_pair(i,INT_MAX);
            }
            else{
                if(NumberToIdx[a[i]].second == INT_MAX){
                    NumberToIdx[a[i]].second = i;
                    MinDist = min(MinDist , (NumberToIdx[a[i]].second - NumberToIdx[a[i]].first));
                }
    
                else{
                    int d = i - NumberToIdx[a[i]].second; 
                    MinDist = min(MinDist , d);
                }
            }
        }
    
        if(MinDist == INT_MAX)
            return -1;
        
        return MinDist;
    
  • + 0 comments
    def minimumDistances(a):
        dist = float('inf')
        for i in range(len(a)):
            if a[i] in a[i+1:]:
                b = a.index(a[i],i+1,len(a))
                dist = min(dist,abs(i-b))
        if dist == float('inf'):
            return -1 
        else:
            return dist
            
    
  • + 1 comment

    for Python3 Platform

    def minimumDistances(a):
        min_d = 10000
        
        for i in range(len(a)-1):
            for j in range(i+1, len(a)):
                if (a[i] == a[j]):
                    min_d = min(min_d, abs(i-j))
        
        return -1 if min_d == 10000 else min_d
    
    n = int(input())
    a = list(map(int, input().split()))
    
    result = minimumDistances(a)
    
    print(result)