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

后端 未结 15 2232
暖寄归人
暖寄归人 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 07:56

    JavaScript:

    let findFirstMissingNumber = ( arr ) => {
          // Sort array and find the index of the lowest positive element.
          let sortedArr = arr.sort( (a,b) => a-b );
          const lowestPositiveIndex = arr.findIndex( (element) => element > 0 );
    
          // Starting from the lowest positive element
          // check upwards if we have the next integer in the array.
          let i = lowestPositiveIndex;
          while( i < sortedArr.length ) {
            if ( sortedArr[ i + 1 ] !== sortedArr[ i ] + 1 ) {
              return sortedArr[ i ] + 1
            } else {
              i += 1;
            }
          }
        }
    
        console.log( findFirstMissingNumber( [3, 4, -1, 1, 1] ) ); // should give 2
        console.log( findFirstMissingNumber( [0, 1, 2, 0] ) ); // should give 3

    0 讨论(0)
  • 2021-02-01 07:58

    I solved the problem using set in python3. It is very simple 6LOC. time complexity: O(n).

    Remember: Membership check in set is O(1)

    def first_missing_positive_integer(arr):
        arr = set(arr)
        for i in range(1, len(arr)+2):
            if i not in arr:
                return i
    
    0 讨论(0)
  • 2021-02-01 08:00

    This is in Java. Time complexity f O(N) and space complexity O(1)

    private static int minimum_positive_integer(int[] arr) {
            int i = 0;
            int j = arr.length - 1;
    
            //splitting array
            while (i < j) {
                if (arr[i] > 0) {
                    i++;
                }
    
                if (arr[j] <= 0) {
                    j--;
                }
    
                if (arr[i] <= 0 && arr[j] > 0) {
                    int t = arr[i];
                    arr[i] = arr[j];
                    arr[j] = t;
    
                    i++;
                    j--;
                }
            }
            int len_positive = i;
    
            if (arr[i] > 0) len_positive++;
    
            for (i = 0; i < len_positive; i++) {
                int abs = Math.abs(arr[i]);
                if (abs <= len_positive) {
                    int index = abs - 1;
                    arr[index] = -abs;
                }
            }
    
            for (i = 0; i < len_positive; i++) {
                if(arr[i] > 0) return  i + 1;
            }
    
            return len_positive + 1;
        }
    
    0 讨论(0)
  • 2021-02-01 08:01
    public int FindMissing(){
        var list = new int[] { 6, -6, 4, 5 };
        list = list.OrderBy(x => x).ToArray();
        var maxValue = 0;
        for (int i = 0; i < list.Length; i++)
        {
            if (list[i] <= 0)
            {
                continue;
            }
            if (i == list.Length - 1 ||
                list[i] + 1 != list[i + 1])
            {
                maxValue = list[i] + 1;
                break;
            }
        }
        return maxValue;
    }
    
    1. sort the data by ascending order:
    2. for loop the data
      • if value less than equal to 0 then do nothing and skip.
      • check if the current index value plus 1 was equal to next index value
        • if yes, continue with the loop.
        • if no, current index value plus 1 will be the missing positive integer
    0 讨论(0)
  • 2021-02-01 08:03

    Here's a Python 3 implementation of pmcarpan's answer.

    def missing_int(nums: MutableSequence[int]) -> int:
        # If empty array or doesn't have 1, return 1
        if not next((x for x in nums if x == 1), 0):
            return 1
    
        lo: int = 0
        hi: int = len(nums) - 1
        i: int = 0
        pivot: int = 1
    
        while i <= hi:
            if nums[i] < pivot:
                swap(nums, i, hi)
                hi -= 1
            elif nums[i] > pivot:
                swap(nums, i, lo)
                i += 1
                lo += 1
            else:
                i += 1
    
        x = 0
        while x <= hi:  # hi is the index of the last positive number
            y: int = abs(nums[x])
            if 0 < y <= hi + 1 and nums[y - 1] > 0:  # Don't flip sign if already negative
                nums[y - 1] *= -1
            x += 1
    
        return next((i for i, v in enumerate(nums[:hi + 1]) if v >= 0), x) + 1
    

    Tests:

    def test_missing_int(self):
        assert func.missing_int([1, 2, 1, 0]) == 3
        assert func.missing_int([3, 4, -1, 1]) == 2
        assert func.missing_int([7, 8, 9, 11, 12]) == 1
        assert func.missing_int([1]) == 2
        assert func.missing_int([]) == 1
        assert func.missing_int([0]) == 1
        assert func.missing_int([2, 1]) == 3
        assert func.missing_int([-1, -2, -3]) == 1
        assert func.missing_int([1, 1]) == 2
        assert func.missing_int([1000, -1]) == 1
        assert func.missing_int([-10, -3, -100, -1000, -239, 1]) == 2
        assert func.missing_int([1, 1]) == 2
    
    0 讨论(0)
  • 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)
      
    0 讨论(0)
提交回复
热议问题