11.First Missing Positive

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

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

Solution: (Hash set)

class Solution
{
public:
    int firstMissingPositive(vector<int> &nums)
    {

        unordered_set<int> s;
        for (int i = 0; i < nums.size(); i++)
        {
            s.insert(nums[i]);
        }

        for (int i = 1; i < INT_MAX; i++)
        {
            if (s.find(i) == s.end())
            {
                return i;
            }
        }

        return 0;
    }
};

Time Complexity: O(n) Space Complexity: O(n)

Solution:

Algorithm: Creating an array of all positive numbers Iterate and mark the index of a each number as -ve Finally, a number which is not negative is the missing number.

Time Complexity: O(n) Space Complexity: O(n)

Solution:

Algorithm: Using positive number each number as index

Time Complexity: O(n) Space Complexity: O(1)

Last updated

Was this helpful?