Problem Statement

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

You must 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:

Problem Link

First Missing Positive - LeetCode

Reference Video

https://www.youtube.com/watch?v=-lfHWWMmXXM

Code

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        long long int n = nums.size();
        
        for(long long int i=0;i<n;i++)
        {
            **if(nums[i]<0)
                continue;**
            long long int correctPos = nums[i]-1;
            
            while(nums[i]>=1 && nums[i]<=n && nums[i]!=nums[correctPos])
            {
                swap(nums[i],nums[correctPos]);
                correctPos = nums[i]-1;
            }
        }
        for(long long int i=0;i<n;i++)
        {
            if(i+1!=nums[i])
                return i+1;
        }
        return n+1;
        
    }
};

Time complexity O(n)

Note: Inside the while loop if we give the condition as while(nums[i]>=1 && nums[i]<=n && nums[i]!=i+1) then it will give TLE incase of array having duplicate elements