Find multiple missing elements in sorted an array

class FindMultpleMissingElementsInAnArray {

    static int getMissingElement(int[] array) {

        // Corner case 

        if(array.length == 0) {

            System.out.println("Array is empty");

            return -1;

        }

        int sum = 0;

         for(int i = 0; i < array.length; i++) {

            sum += array[i];

        }

        int n = array[array.length - 1]; // last element in list

        int sumOfNNaturalNumbers = n*(n+1)/2;

        return sumOfNNaturalNumbers - sum;

    }

    static void printMissingElements(int[] array) {

        // Corner case 

        if(array.length == 0) {

            System.out.println("Array is empty");

        }

        int diff = array[0];

         for(int i = 0; i < array.length; i++) {

            if(array[i] - i != diff) {

                while(diff < array[i] - i) {

                    int missingElement = diff + i;

                    System.out.println("Missing element is : " + missingElement);

                    diff++;

                }

            }

        }

    }    

public static void main (String[] args) {

int[] array = new int[] {6,7,8,9,11,12,15,16,19,20,21};

printMissingElements(array);

}

}


Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance