-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirstMissingPositive.cpp
74 lines (59 loc) · 1.7 KB
/
FirstMissingPositive.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//////////////////////////////////////CODE STUDIO////////////////////////////////////
// MEDIUM
//////////////////////////////////////__41__LEETCODE////////////////////////////////////
// HARD
// Q. FInd the next missing positive in the given array
/*
If positive elements in the array are in range of 1 --> n
1) if any number from range is missing , in eg 2, {1,3,4} here 2 is missing
therefore next smallest positive is 2
2) if all numbers are in range then next missing positive would be n+1
in eg 1, {1,2,3,4,5} here all are in range and nothing is missing between 1-->5
therefore next positive is 6 (5+1)
For eg: arr[]={1,2,3,4,5}
Here the next postive number would be 6
For eg: arr[]={-2,1,3,4}
Here the next positive number would be 2
*/
// BETTER / GOOD APPROACH:
/*
1. For all elements <= 0, we will change them to n+1;
so that every element is in range 1 --> n
2. Take an index = (number present at the i) - 1;
if index < n
then make arr[index] negative
3. Now, If elements >=0
return i+1
4. Return n+1 in case everything is in range, so that next missing +ve would be n+1
*/
#include <bits/stdc++.h>
int firstMissing(int arr[], int n)
{
// Write your code here.
// 1.
for (int i = 0; i < n; i++)
{
if (arr[i] <= 0)
{
arr[i] = n + 1;
}
}
// 2.
for (int i = 0; i < n; i++)
{
int index = abs(arr[i]) - 1;
if (index < n)
{
arr[index] = -arr[index];
}
}
// 3.
for (int i = 0; i < n; i++)
{
if (arr[i] >= 0)
{
return i + 1;
}
}
return n + 1;
}