Problem
The list holds n distinct numbers taken from 0, 1, …, n, so exactly one number in that range is missing. Find it. (Hint: compare the expected total with the actual total.)
Implement missing_number(numbers).
Input
numbers: n distinct numbers from 0 to n.
Output
Return the missing number.
Constraints
0 ≤ n ≤ 100,000
Examples
Input:
numbers = [3, 0, 1]
Expected output:
expected = 2
Input:
std::vector<long long> numbers = {3, 0, 1};
Expected output:
long long expected = 2;
Input:
long[] numbers = new long[] {3, 0, 1};
Expected output:
long expected = 2;
Explanation
n = 3, so the range is 0–3; 2 is missing.
Input:
numbers = [0]
Expected output:
expected = 1
Input:
std::vector<long long> numbers = {0};
Expected output:
long long expected = 1;
Input:
long[] numbers = new long[] {0};
Expected output:
long expected = 1;
Explanation
n = 1 and the range is 0–1; 1 is missing.
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
The numbers should match the full range from 0 through n except for one hole.
Hint 2
Compare what the complete range would total against what the list actually totals.
Hint 3
Watch for the case where the missing value is 0 or n.
Expected complexity
O(n) time, O(1) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.