This is an interview question, but I couldn't solve it in time, so posting it here:
Given a sorted array of n integers where each integer is in the range from 0 to m-1
and m > n
. Find the smallest number that is missing from the array.
Examples
Input: {0, 1, 2, 6, 9}
, n = 5
,m = 10
Output: 3
Input: {4, 5, 10, 11}
, n = 4
, m = 12
Output: 0
The code for this is as follows:
int findFirstMissing(int array[], int start, int end) {
if(start > end)
return end + 1;
if (start != array[start])
return start;
int mid = (start + end) / 2;
if (array[mid] > mid)
return findFirstMissing(array, start, mid);
else
return findFirstMissing(array, mid + 1, end);
}
Now, the question is that input array can have duplicates also:
input = [0, 1, 1, 2, 3, 3, 4, 5, 5, 7]
output = 6
How do I solve it efficiently? What kind of optimizations can be applied?