Minimum Distances HackerRank

 class Result {


    /*
     * Complete the 'minimumDistances' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts INTEGER_ARRAY a as parameter.
     */

    public static int minimumDistances(List<Integer> a) {
        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
        ArrayList<Integer>aa=new ArrayList<Integer>();
        for(int i=0;i<a.size();i++){
            if(!map.containsKey(a.get(i))){
                map.put(a.get(i),i);
            }
            else{
                int b=map.get(a.get(i));
                aa.add(i-b);
            }
        }
        if(aa.size()==0){
            return -1;
        }
        else
          return Collections.min(aa);
    }

}

Approach:
Here we will use a HashMap and an ArrayList. In HashMap we will store
unique elements as keys and with their value as their incoming index in the
given ArrayList a. If that element is not present in the map, it will get store
else if it is present already then we will get the index of its previous storage and
by subtracting it with the current index (as we are traversing on ArrayList a).
That value we will store in another ArrayList aa. In such a manner we will
traverse the whole given list.

Now if the size of our new list aa is 0 it means no element was duplicate
so we will return -1 else we will return min of this ArrayList.
This ArrayList aa contains difference values between elements and since we want
to get a minimum difference of indexes so we will return a minimum of this arraylist.


Time :O(N)
Space:O(Unique Keys in HashMap and additional space of ArrayList consisting
an integer value for duplicates)

Thanks for Reading.😇

Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks