-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathfirst_missing_positive.cpp
58 lines (46 loc) · 1.26 KB
/
first_missing_positive.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
*/
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<conio.h>
using namespace std;
// function prototype
void printArray(int arr[], int n);
int firstMissingNumber(int arr[], int n);
int firstMissingNumber(int arr[], int n)
{
int index, temp;
for(index=0;index<n;index++)
{
while(arr[index]>=1 && arr[index]<=n && arr[index]!=arr[arr[index]-1])
{
temp = arr[arr[index]-1];
arr[arr[index]-1] = arr[index];
arr[index] = temp;
}
}
for(index=0;index<n;index++)
{
if((index+1)!=arr[index])
return index+1;
}
return n+1;
}
int main()
{
int n;
cin>>n;
int arr[n], index, res;
for(index=0;index<n;index++)
cin>>arr[index];
// finding the first positive missing number
printf("\n");
res = firstMissingNumber(arr,n);
cout<<res;
return 0;
}