Let the numbers in the array be 1,2,4,6,3,7,8,10,9 (total 9 numbers without repetition). I will try to solve this by using following algorithm that randomly came to my mind.
get_missing_number_1(array){
array=Sort(array);
for(i=0 to i
temp=array[i+1] - array[i] ;
if(temp>1) return array[i]+1;
}
}
To make things easy, I will give a dry run of this algorithm. Let the array after sorting is 1,2,3,4,6,7,8,9,10. Only number five is missing. For consecutive numbers in array i.e 2-1 is 1, 3-2 is 1 but 6-4 is 2, so 5 is missing.
But there exists a very simple method to find the missing number. Just do this
get_missing_number_2(array){
sum_array= sum of all numbers in array;
sum_1_to_10= sum of all numbers from 1 to 10;
missing_number= sum_1_to_10 - sum_array;
return missing_number
}
So, Did we wasted your time in the analysis of first algorithm?
The second method uses a heuristic and exploits particular properties of the problem. But there is lesser chance to solve the problem if it is generalized using a heuristic. Think, if array size is 8; that is, two numbers are missing , which of the above algorithms can be modified to find both the numbers?
The complexity of algorithm get_missing_number_1 is O(n log n) and get_missing_number_2 is O(n), but the first one is more generic.
Now question arises if there exists an algorithm that finds the missing number for generalized problem in linear time. The algorithm discussed get_missing_number_1 has time complexity O(n log n).
So, let's do divide and conquer. The image below is self-explanatory. The method used is to divide the problem by partitioning.
The time complexity comes out to be n + n/2 + n/4 ......... ~ O(n). {assuming partition divides the problem approximately into 2 equal parts}
On slight modification this algorithm can be used to find out multiple missing numbers. For that we have to follow multiple branches with missing numbers.