Skip to content

Commit

Permalink
finding first missing positive
Browse files Browse the repository at this point in the history
  • Loading branch information
ayush9919 authored Oct 31, 2022
1 parent dbd4685 commit af8bb78
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions firstmissingpositive.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra space.
*/
class Solution
{
public:
int firstMissingPositive(int A[], int n)
{
for(int i = 0; i < n; ++ i)
while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i])
swap(A[i], A[A[i] - 1]);

for(int i = 0; i < n; ++ i)
if(A[i] != i + 1)
return i + 1;

return n + 1;
}
};

0 comments on commit af8bb78

Please sign in to comment.