-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathFind_Missing_and_Repeating.cpp
More file actions
61 lines (46 loc) · 1.19 KB
/
Find_Missing_and_Repeating.cpp
File metadata and controls
61 lines (46 loc) · 1.19 KB
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
#include <iostream>
#include <vector>
using namespace std;
void findMissingAndDuplicate(const vector<int>& arr) {
int n = arr.size();
int xorAll = 0;
for (int i = 0; i < n; i++) {
xorAll ^= arr[i];
xorAll ^= (i + 1);
}
// Find the rightmost set bit in xorAll
int rightmostSetBit = xorAll & -xorAll;
int missing = 0, duplicate = 0;
for (int i = 0; i < n; i++) {
if (arr[i] & rightmostSetBit) {
missing ^= arr[i];
} else {
missing ^= (i + 1);
}
}
duplicate = xorAll ^ missing;
cout << "Missing Number: " << missing << endl;
cout << "Duplicate Number: " << duplicate << endl;
}
// Test Cases
// ->Test Case1:
// {4, 2, 7, 1, 5, 6, 2, 3}
// Missing Number: 8
// Duplicate Number: 2
// ->Test Case2:
// {1, 1, 3, 3, 5, 6, 6, 8}
// Missing Number: 4
// Duplicate Number: 1
// ->Test Case3:
// {9, 8, 7, 6, 5, 4, 3, 2, 1, 1}
// Missing Number: 10
// Duplicate Number: 1
// ->Test Case4:
// {10, 9, 8, 6, 5, 4, 3, 2, 1, 7}
// Missing Number: 6
// Duplicate Number: 7
int main() {
vector<int> arr = {4, 3, 2, 7, 8, 2, 1, 5};
findMissingAndDuplicate(arr);
return 0;
}