forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
first_missing_positive_integer.c
53 lines (49 loc) · 1.06 KB
/
first_missing_positive_integer.c
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
#include <stdio.h>
#include <stdlib.h>
int main(){
int n;
printf("Enter the value of n: ");
scanf("%d\n",&n);
printf("Enter the array:\n");
int *arr = (int*)malloc(n * sizeof(int));
for (int i = 1; i <= n; ++i)
{
scanf("%d", &arr[i]);
}
if (arr == NULL) {
printf("Memory not allocated.\n");
return 0;
}
else {
for (int i = 1; i <= n; i++) {
if (arr[i] <= 0 || arr[i] > n)
continue;
int x = arr[i];
while (arr[x] != x) {
int next_ele = arr[x];
arr[x] = x;
x = next_ele;
if (x <= 0 || x > n)
break;
}
}
int ans = n + 1;
for (int i = 1; i <= n; i++) {
if (arr[i] != i) {
ans = i;
break;
}
}
printf("%d", ans);
}
return 0;
}
/*
Time Complexity: O(N)
Space Complexity: O(1)
OUTPUT
Enter the value of n: 4
Enter the array:
3 4 -1 1
2
*/