Posts First missing positive
Post
Cancel

First missing positive

Given an unsorted integer array nums, find the smallest missing positive integer.

Follow up: Could you implement an algorithm that runs in O(n) time and uses constant extra space.?

Example 1:

Input: nums = [1,2,0] Output: 3

Example 2:

Input: nums = [3,4,-1,1] Output: 2

Example 3:

Input: nums = [7,8,9,11,12] Output: 1

Constraints:

  • 0 <= nums.length <= 300
  • -231 <= nums[i] <= 231 - 1

Solution

cue words from question

unsorted : means that we cannot use binary search Positive intgers : means we do not care about negative numbers as well as duplicates

So from above we conclude that whatever we do needs to be inplace.

Idea 1 : Just put the numbers in their position ex: num[i] should be at num[num[i]]

this fails because if array size is less than num[i] then we get seg fault;

Idea 2: get max and min from array in range [1,max] now we subtract min from every number such that our range becomes >= our array size now we can place our numbers in their position ex : num[i] should be at num[num[i]-min]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {


        if(nums.size()==0)
            return 1;
        if(nums.size()==1)
            return nums[0]!=1?1:2;

        int i=0;
        int min_a=INT_MAX,max_a=INT_MIN;
        for(int i=0;i<nums.size();i++)
        {

            if(nums[i]>0)
            {min_a=min(min_a,nums[i]);
             max_a = max(max_a,nums[i]);}
        }
        if(min_a!=1)
            return 1;

        while(i<nums.size())
        {

            if(nums[i]>0 && nums[i]-min_a < i && nums[nums[i]-min_a]!=nums[i])
            {
                swap(nums[nums[i]-min_a],nums[i]);
            }
            else
                i++;
        }

      int ans=1;
        for(int i=0;i<nums.size();i++)
            if(ans == nums[i])
                ans++;
        return ans;




    }
};
This post is licensed under CC BY 4.0 by the author.