Find a Missing Number From a Sequence of Consecutive Numbers

Objective : You have been asked to Write an algorithm Find a Missing Number From a Sequence of Consecutive Numbers

Input:  Array, arrA[] with a missing number and Range

Output : missing number

Approach:

  • Approach is very simple, Add all the given numbers say S
  • Calculate sum of N numbers by formula n(n+1)/2 , say N
  • Find missing number m = N-S


Example : suppose array given is  {1,2,3,4,5,6,8,9,10} and range is 10.

So N will be sum of 1 to 10  = 10(10+1)/2 = 55

S will be sum of all the array elements which is = 48

So missing number will be = 55-48 = 7

Complete Code:

//find the missing number from the sequence of consecutive number
//Approach is very simple, Add all the given numbers say S
//Calculate sum of N numbers by formula n(n+1)/2 , say N
//Find missing number m = N-S
public class FindMissingNumber {
int Sum;
int Sum_N;
public int missingNumber(int [] arrA, int size){
Sum_N = size*(size+1)/2;
for(int i=0;i<arrA.length;i++){
Sum +=arrA[i];
}
return Sum_NSum;
}
public static void main(String args[]){
int [] arrA = {1,2,3,4,5,7,8,9,10};
System.out.println("Missing number is :" + (new FindMissingNumber()).missingNumber(arrA,10));
}
}

Output :
Missing number is :6