forked from shivprime94/Data-Structure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirst Missing Positive
69 lines (57 loc) · 1.43 KB
/
First Missing Positive
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
/* Java program to find the smallest
positive missing number */
import java.io.*;
class FirstMissingPositive {
// Function to find smallest positive
// missing number.
static int findMissingNo(int []arr, int n)
{
// to store current array element
int val;
// to store next array element in
// current traversal
int nextval;
for (int i = 0; i < n; i++) {
// if value is negative or greater
// than array size, then it cannot
// be marked in array. So move to
// next element.
if (arr[i] <= 0 || arr[i] > n)
continue;
val = arr[i];
// traverse the array until we
// reach at an element which
// is already marked or which
// could not be marked.
while (arr[val - 1] != val) {
nextval = arr[val - 1];
arr[val - 1] = val;
val = nextval;
if (val <= 0 || val > n)
break;
}
}
// find first array index which is
// not marked which is also the
// smallest positive missing
// number.
for (int i = 0; i < n; i++) {
if (arr[i] != i + 1) {
return i + 1;
}
}
// if all indices are marked, then
// smallest missing positive
// number is array_size + 1.
return n + 1;
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 2, 3, 7, 6, 8, -1, -10, 15 };
int arr_size = arr.length;
int missing = findMissingNo(arr, arr_size);
System.out.println( "The smallest positive"
+ " missing number is " + missing);
}
}