Skip to content

Fix bug #162 #163

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions C++/Find_Missing_and_Repeating.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}