forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
missing_number.py
40 lines (32 loc) · 881 Bytes
/
missing_number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def find_missing_number(nums: list[int]) -> int:
"""
Finds the missing number in a list of consecutive integers.
Args:
nums: A list of integers.
Returns:
The missing number.
Example:
>>> find_missing_number([0, 1, 3, 4])
2
>>> find_missing_number([4, 3, 1, 0])
2
>>> find_missing_number([-4, -3, -1, 0])
-2
>>> find_missing_number([-2, 2, 1, 3, 0])
-1
>>> find_missing_number([1, 3, 4, 5, 6])
2
>>> find_missing_number([6, 5, 4, 2, 1])
3
>>> find_missing_number([6, 1, 5, 3, 4])
2
"""
low = min(nums)
high = max(nums)
missing_number = high
for i in range(low, high):
missing_number ^= i ^ nums[i - low]
return missing_number
if __name__ == "__main__":
import doctest
doctest.testmod()