A list holds n different numbers taken from 0, 1, ..., n. Exactly one number of that range is missing.
What to build
A program that finds the missing number in O(n) time with O(1) extra space.
Requirements
- Print the one number between 0 and n that is not in the list.
- Use arithmetic on the sum instead of a set, to practise stating space complexity.
Input
The first line has n. The second line has the n different numbers.
Output
The missing number.
Constraints
1 ≤ n ≤ 10⁵.
Example
Input:
3
3 0 1
Output:
2
Why it works
The numbers 0 to n add up to n(n+1)/2. The list has everything except one number, so the difference between that total and the list's sum is exactly the missing number.
Examples
3 3 0 1
2
2 0 1
2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The numbers are 0 to n with exactly one missing, so the full total is n(n+1)/2.
Hint 2
The answer is the full total minus the sum of the list.
Hint 3
No sorting and no set are needed: O(n) time and O(1) extra space.
Solution
Show one correct solution (try it yourself first)
n = int(input()) nums = list(map(int, input().split())) print(n * (n + 1) // 2 - sum(nums))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step