-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmissingNumber.cpp
104 lines (94 loc) · 2.51 KB
/
missingNumber.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* Search the missing number in an array*/
#include<bits/stdc++.h>
using namespace std;
// class Solution
// {
// public:
// int missingNumber(vector <int> arr, int n)
// {
// int n1 = arr.size();
// for(int i = 1; i<= n; i++ )
// {
// int flag = 0;
// for(int j = 0; j< n1; j++)
// {
// if(arr[j] == i)
// {
// flag = 1;
// break;
// }
// }
// if(flag == 0)
// {
// return i;
// }
// }
// return -1;
// }
// };
// this is the brute force solution. whose time complexity is o(n^2). it may stuck in infinite loop.
// class Solution
// {
// public:
// int missingNumber(vector <int> arr, int n)
// {
// int n1 = arr.size();
// int hash[n+1] = {0};
// for(int i = 0; i< n1; i++)
// {
// hash[arr[i]]++;
// }
// for(int i = 1; i< n; i++)
// {
// if(hash[i] == 0)
// {
// return i;
// }
// }
// return -1;
// }
// };
// this is better method the time complexity is o(n1+n) or o(2n).
// class Solution
// {
// public:
// int missingNumber(vector <int> arr, int n)
// {
// int sum = n*(n+1)/2;
// int addition = 0;
// int n1 = arr.size();
// for(int i = 0; i< n1; i++)
// {
// addition = addition + arr[i];
// }
// return sum - addition;
// }
// };
// the time complexity of this code is o(n).but their is stil is a problem if the input is 10^5 then sum = almost 10^10 which we cannot store in int variable we need to use long.
class Solution
{
public:
int missingNumber(vector <int> arr, int n)
{
int xor1 = 0, xor2 = 0;
int n1 = arr.size();
for(int i = 0; i< n1; i++)
{
xor2 = xor2 ^ arr[i];
xor1 = xor1 ^ (i+1);
}
xor1 = xor1 ^ n;
// because inside the loop the xor1 one is goes to untill 4 in this case.
return xor1 ^ xor2;
}
};
// the time complexity of this code is o(n).So the sum and the xor method is the optimal method.
int main()
{
vector <int> v = {1,2,4,5};
int size = 5;
Solution s;
int a = s.missingNumber(v, size);
cout<< a;
return 0;
}