Find Missing Number
Question: You are given a sorted array A of n distinct integers, drawn from 1 to m where n<m. That is, A is a subset of [1,2,...,m]. Implement an O(logn) time algorithm (i.e., write a function) to find the smallest non-negative integer that is missing in A given as a parameter. For example, when A is [1, 2, 3, 5, 7, 8, 10], the function must return 4.
Solution:
static int FindMissingNumber(int[] numberList, int n) {
int left = 0, right = n - 1;
while (left <= right) {
int middle = (left + right) / 2;
//If first element that is not index+1, then missing element = middle +1
if (numberList[middle] != middle + 1 && numberList[middle - 1] == middle) {
return (middle + 1);
}
//If not the first element
//Search missing element in left side
if (numberList[middle] != middle + 1) {
right = middle - 1;
}
//Search right side
else {
left = middle + 1;
}
}
//If no element missing return 0;
}