Minimum Distances between Similar numbers in an array

By | June 8, 2021

The distance between two array values is the number of indices between them. Given , find the minimum distance between any pair of equal elements in the array. If no such value exists, return -1.

Example

arr = [3, 2, 1, 2, 3];

Minimum Distance = 2 (Distance between 2’s)


public static int minimumDistances(List<Integer> a) {
    
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    
    int minDistance =  Integer.MAX_VALUE;
    
    for(int i = 0; i < a.size(); i++){
        int element = a.get(i);
        if(!map.containsKey(element)){
            map.put(element, i);
        }else{
            int lastIndex = map.get(element);
            int distance = i - lastIndex;
            minDistance = Math.min(minDistance, distance);
        }
    }
    
    return minDistance == Integer.MAX_VALUE ? -1 : minDistance;
}


Leave a Reply

Your email address will not be published. Required fields are marked *