Find the Missing Number

You are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list. Write an efficient code to find the missing integer.


Solution 1: using the formula n(n+1) / 2

Code:

package microsoftInterviewPrep;

public class MissingNumber {
   
    static void findMissingNumber(int[] a){

        //we add one to the length since we are missing one element in the array
        // we should include that also to get our results correct
        int n = a.length + 1;
        int total = n* (n+1) /2;
       
        int arraytotal = 0;
        for(int i=0; i<a.length; i++){
            arraytotal += a[i];
        }
       
        int res = total - arraytotal;
       
        System.out.println("Missing number is "+ res);
    }
   
    public static void main(String[] args){
       
        int[] a= {1, 2, 4, 6, 3, 7, 8};
        findMissingNumber(a);
       
    }

}

Output:
Missing number is 5


Solution 2: Using XOR

Code:

package microsoftInterviewPrep;

public class MissingNumber2 {
   
    static void findMissingNumber(int[] a){

        int x1 = a[0];
        int x2 = 1;
       
        for(int i=1; i<a.length; i++){
           
            x1 = x1 ^ a[i];
           
        }
       
        // 1 is added to length since the number of elements will be one more when we
        // include the count of missing element
       
        for(int i=2; i<= a.length+1; i++){
           
            x2 = x2 ^ i;
        }
       
        int res = x1 ^ x2;
       
        System.out.println(res);
       
    }
   
    public static void main(String[] args){
       
        int[] a= {1, 2, 4, 6, 3, 7, 8};
        findMissingNumber(a);
       
    }

}


Output:

5



 

Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Second Largest Element

Check if a number is a power of another number