Repository containing solution for #SdeSheetChallenge by striver
Given an unsorted array of size n. Array elements are in the range from 1 to n. One number from set {1, 2, …n} is missing and one number occurs twice in the array. Find these two numbers.
x - y = a1
and x^2 - y^2 = a2
then we solve theses two equations and get x + y = a3
.x + y = a3
and x - y = a1
to get x and y, Where x=Missing and y=Repeated.x^y = a
.a
will be set in either x or y.// codestudio
#include <bits/stdc++.h>
pair<int, int> missingAndRepeating(vector<int>& arr, int n)
{
int x = 0, y = 0; // repeating and missing numbers resp.
int i;
int xorNum = 0, setBit;
// xor of all numbers
for (auto num : arr) xorNum ^= num;
// xor with 1 to n
for (int i = 1; i <= n; i++) xorNum ^= i;
// get rightmost set bit no.
setBit = xorNum & ~(xorNum - 1);
// compare and divide into 2 sets
for (int i = 0; i < n; i++) {
if (arr[i] & setBit) {
x ^= arr[i];
} else {
y ^= arr[i];
}
}
for (i = 1; i <= n; i++) {
if (i & setBit)
x ^= i;
else
y ^= i;
}
// number may be swap, recheck to confirm
int xCnt = 0;
for (auto num : arr) {
if (num == x) xCnt++;
}
if (xCnt != 0) return { y, x };
return { x, y };
}