Problem 25
Missing Number
Problem
An array contains N distinct integers, all taken from the range 0 to N. That range has N + 1 numbers, so exactly one of them is missing from the array. Find the missing number. The numbers 0 to N add up to N × (N + 1) / 2. Subtracting the sum of the array from this total leaves exactly the missing number. (XOR-ing all the numbers 0 to N together with all array elements also works.)
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the missing number.
Constraints
1 <= N <= 100000; 0 <= A[i] <= N; all values are distinct
Example input
3 3 0 1
Example output
2
Explanation
Here N = 3, so the range is 0, 1, 2, 3. The array has 3, 0 and 1, so 2 is missing. With the formula: 0 + 1 + 2 + 3 = 6, the array sums to 4, and 6 - 4 = 2.