30
Jan
2020

Hackerrank Equalize the Array (Java)

Java :

static int equalizeArray(int[] arr) {
        int noOfElementsToDelete = 0, countInt = 1, currentInt = 0, numberOfInt = 0, prevInt = 0;

        Arrays.sort(arr);
        prevInt = arr[0];

        for(int i = 1; i < arr.length; i++){
            currentInt = arr[i];

            if(prevInt == currentInt){
                countInt++;
            }else{
                countInt = 1;
            }

            if(numberOfInt < countInt){
                numberOfInt = countInt;
            }

            prevInt = arr[i];
        }

        noOfElementsToDelete = arr.length - numberOfInt;

        return noOfElementsToDelete;
    }

Explanation:

First, sort the array so that counting the number of repeated elements in the array is easier. After sorting, assign the first element of the array arr[0] to prevInt. countInt is set to 1 initially, since prevInt is set to arr[0], so counting begins at 1 automatically.

In the for loop from i = 1, set the currentInt to arr[i], and compare currentInt to prevInt. If they are the same, set countInt to increment by 1. If not, set countInt to 1 so counting can start afresh to count the number of the next repeated element.

The next if loop checks if numberOfInt (initially set to 0) is smaller than countInt, if so, set the numberOfInt to be countInt, so that numberOfInt stores the maximum number of repeated elements counted so far. Before going to the next index i, set prevInt to the current number at index i, so that it can be compared to the next i (current i + 1) in the next loop.

Finally, when the greatest number of repeated elements is found and stored in numberOfInt, get noOfElementsToDelete by using the total number of elements (arr.length) minus numberOfInt.

You may also like...

Leave a Reply

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