Skip to content

Commit c6846cb

Browse files
committed
added first missing positive number progrma
1 parent be29bad commit c6846cb

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Arrays/first_missing_positive.cpp

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

0 commit comments

Comments
 (0)