Skip to content

Instantly share code, notes, and snippets.

@cruxrebels
Created April 20, 2016 16:04
Show Gist options
  • Save cruxrebels/042bb25c65ecb16f138aee056c4e1e2d to your computer and use it in GitHub Desktop.
Save cruxrebels/042bb25c65ecb16f138aee056c4e1e2d to your computer and use it in GitHub Desktop.
Given an unsorted integer array, find the first missing positive integer. Example: Given [1,2,0] return 3, [3,4,-1,1] return 2, [-8, -7, -6] returns 1 Your algorithm should run in O(n) time and use constant space. Tags: InterviewBit Array Problem https://www.interviewbit.com/problems/first-missing-integer/
int Solution::firstMissingPositive(vector<int> &A) {
sort(A.begin(), A.end());
int c = 1;
for (auto const& a : A)
{
if (a<1)
continue;
else if (a==c)
{
++c;
continue;
}
else
break;
}
return c;
}
@shuboy2014
Copy link

Solution must be O(n) and your solution in O(nlogn)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment