An array contains all the integers from 0 to n, except for one number which is missing. Write code to find the missing integer. Can you do it in O(n) time?
Note: This problem is slightly different from the original one the book.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Solutions
Solution 1
Thinking
One number is missing from \(0\ldots n\). A boolean mark array works but uses linear extra space.
After sorting, index should equal value; the first mismatch is the missing number, or \(n\) if none.
sort then scan is the shortest correct solution, in \(O(n\log n)\).