Idea: get the sorted version of L, then find the gap: find an i such that L[i+1]-L[i] is 2 rather than 1.Then the answer is L[i]+1, the number between L[i] and L[i+1].
For example, if the sorted version of L is
[1, 2, 3, 4, 6, 7, 8, 9], then L[4]-L[3] == 2, and we can conclude that the missing number is L[3]+1, i.e., 4+1=5.
def missing_k_C(L):
sorted_L = sorted(L) #L stays the same. sorted_L stores the sorted
#version of the list L
n = len(sorted_L) + 1 #Since the original list had n elmenents, and L
#is one element shorter than the original list,
#to get n, we must add 1 to len(sorted_L)
#Take care of the special cases: the missing element is in the beginning
#or the missing element is at the end
if sorted_L[0] != 1:
return 1
#sorted_L[len(sorted_L)-1] is the same as sorted_L[-1]: it's the last
#element of sorted_L
if sorted_L[-1] != n:
return n
#The main loop: find the i such that there is a gap between
#L[i] and L[i+1]
for i in range(len(sorted_L)-1):
if sorted_L[i+1]-sorted_L[i] != 1:
return sorted_L[i] + 1
Here's another idea: sort the list, and then check of sorted_L[0] is 1, if sorted_L[1] is 2, .... and stop when you find a mismatch.
def missing_k_D(L):
sorted_L = sorted(L)
for i in range(len(sorted_L)):
#i = 0, ...., n-2
if sorted_L[i] != i+1:
return i+1
return len(sorted_L) + 1