• + 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; 
    }