from random import shuffle,randint import sys def swap(a,i,e): tmp = a[i] a[i] = a[e] a[e] = tmp def restore(a,m): for i in range(0,len(a)): a[i] += m def findSmallestMissing(a): n = len(a) m = min(a) for i in range(0,n): a[i] = a[i] -m i = 0 n = len(a) while (i < n): print('| ',i,'|',n,'|',a[0:i],'|', a[i:n],'|',a[n:len(a)], '||') if (a[i] == i): # a[i] already equals i, nothing more to do i=i+1 else: if (a[i] < i): # a[i] is strictly less than i # This means a[i] is a repeated element and cannot be missing swap(a,i,n-1) # Place a[i] in the range of elements that cannot be the missing one n=n-1 # reduce n by 1 else: e=a[i] # Let us call e = a[i] if (e < n): if (a[e] == e): # if a[e] already has e in it, e cannot be missing swap(a,i,n-1) n = n -1 else: # otherwise, place a[e] = e and bring a[i] = a[e] e = a[i] swap(a,i,e) else: # if e >= n swap(a,i,n-1) # then a[i] cannot be missing n = n-1 print('| ',i,'|',n,'|',a[0:i],'|',a[i:n],'|',a[n:len(a)], '') for i in range(0,n): if (a[i] != i): restore(a,m) print ( (i+m),' is missing') return (i+m) restore(a,m) print( (n+m), 'is missing') return (n+m) # def test(n): # # Create an array of elements in the range 0, n # a=[] # for i in range(0,n): # a.append(i) # shuffle(a) # scramble # print(a) # # Now mess up 10 elements # r = randint(5,n-1) # m = n # for k in range(0,10): # j = randint(0,n-1) # if (a[j] >= r): # m = min(m,a[j]) # print('Delete:',j,a[j]) # a[j] = n + randint(2,n) # Just increase a[j] # r = findSmallestMissing(a) # if (r == m): # return # else: # print('Failed: ') # print('\t a: ',a) # print('\t Smallest missing should be :',m,' your code says: ',r) # sys.exit(1) # for i in range(0,50000): # test(100) #findSmallestMissing([11,3,2,0,4,6,7,9,1,11,13,11]) findSmallestMissing([0,3,2,0,4,6,7,9,1,11,13,11])