The challenge
Write a function that takes a shuffled list of unique numbers from 1
to n
with one element missing (which can be any number including n
). Return this missing number.
Note: huge lists will be tested.
Examples:
[1, 3, 4] => 2
[1, 2, 3] => 4
[4, 2, 3] => 1
The solution in Python code
Option 1:
def find_missing_number(a):
n = len(a) + 1
return n * (n + 1) // 2 - sum(a)
Option 2:
def find_missing_number(nums):
return sum(range(1,len(nums)+2))-sum(nums)
Option 3:
def find_missing_number(numbers):
if numbers == []:return 1
diff = list(set(range(1, len(numbers)+1))- set(numbers))
if diff == []:return max(numbers)+1
return diff[0]
Test cases to validate our solution
test.assert_equals(find_missing_number([2, 3, 4]), 1)
test.assert_equals(find_missing_number([1, 3, 4]), 2)
test.assert_equals(find_missing_number([1, 2, 4]), 3)
test.assert_equals(find_missing_number([1, 2, 3]), 4)