In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. This question was asked by Stri
I didn't test it in detail, but for sorted array here is how I would approach it, any improvements are welcome. constrains:
constant space
solution:
start with lowest positive integer (i.e. lpi <- 1)
while parsing the array, if lpi is already in the array, increment it
lpi is now the lowest positive integer not available in the array
simple python function will be as follows:
def find_lpi(arr):
lpi = 1
for i in arr:
if lpi == i:
lpi += 1
return lpi
if the array is unsorted, the following could be alternative solution.
first create a binary array, X, of zeroes with length max(arr). For each item in the array mark the index of the X, as 1 return the smallest index with 0
the following is a simple implementation satisfying
constant space complexity constraints.
def find_lpi(arr):
x = [0 for x in range(max(arr)+1)]
for i in arr:
x[i] = 1
for i in range(1,len(x)):
if x[i] ==0:
return i
return len(x)