-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathSmallest positive missing number
66 lines (51 loc) · 1.21 KB
/
Smallest positive missing number
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
#You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the array.
Example 1:
Input:
N = 5
arr[] = {1,2,3,4,5}
Output: 6
Explanation: Smallest positive missing
number is 6.
#Answer
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
int findMissing(int arr[], int n){
for(int i=0;i<n;i++){
if(arr[abs(arr[i])-1] > 0 && (abs(arr[i])-1) < n)
arr[abs(arr[i])-1] = - arr[abs(arr[i])-1];
}
for(int i=0;i<n;i++){
if(arr[i]>0){
return i+1;
}
}
return n+1;
}
// Functio to find first smallest positive
// missing number in the array
int missingNumber(int arr[], int n) {
// Your code here
int j=0;
for(int i=0;i<n;i++){
if(arr[i]<=0 || arr[i]>n){
swap(arr[j],arr[i]);
j++;
}
}
return findMissing(arr+j,n-j);
}
// { Driver Code Starts.
int missingNumber(int arr[], int n);
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)cin>>arr[i];
cout<<missingNumber(arr, n)<<endl;
}
return 0;
} // } Driver Code Ends