Page cover

First Missing Integer

Given an unsorted integer array, find the first missing positive integer.

Brute Force

Code
int Solution::firstMissingPositive(vector<int> &A) {
    for(int i = 1; i <= A.size() + 1; i++) {
        bool found = false;
        for(int j = 0; j < A.size(); j++)
            if(A[j] == i) {
                found = true;
                break;
            }
        if(!found)
            return i;
    }
    return -1;
}

Time Complexity: O(n2)O(n^2)​

Space Complexity: O(1)O(1)

Using Sorting

Code

Time Complexity: O(nlog⁑n)O(n\log n)​

Space Complexity: O(1)O(1)

Using lookup table

Code

Time Complexity: O(n)O(n)

Space Complexity: O(n)O(n)

Optimal Solution Cyclic Sort

Code

Time Complexity: O(n)O(n)​

Space Complexity: O(1)O(1)

Last updated