Given an array of integers, find the first missing positive integer in linear time and constant space

后端 未结 15 2270
暖寄归人
暖寄归人 2021-02-01 07:17

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

15条回答
  •  臣服心动
    2021-02-01 08:03

    I didn't test it in detail, but for sorted array here is how I would approach it, any improvements are welcome. constrains:

    • linear time
    • 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

    • linear time
    • 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)
      

提交回复
热议问题