Skip to content

Instantly share code, notes, and snippets.

@webber2408
Created October 8, 2022 19:06
Show Gist options
  • Save webber2408/00a60de32f462dad8e7544f6d32cf070 to your computer and use it in GitHub Desktop.
Save webber2408/00a60de32f462dad8e7544f6d32cf070 to your computer and use it in GitHub Desktop.
Approach-2) Find Missing & Repeating No. (XOR - Bit Manipulation)
vector < int >Solution::repeatedNumber (const vector < int >&arr) {
/* Will hold xor of all elements and numbers from 1 to n */
int xor1;
/* Will have only single set bit of xor1 */
int set_bit_no;
int i;
int x = 0; // missing
int y = 0; // repeated
int n = arr.size();
xor1 = arr[0];
/* Get the xor of all array elements */
for (i = 1; i < n; i++)
xor1 = xor1 ^ arr[i];
/* XOR the previous result with numbers from 1 to n */
for (i = 1; i <= n; i++)
xor1 = xor1 ^ i;
/* Get the rightmost set bit in set_bit_no */
set_bit_no = xor1 & ~(xor1 - 1);
/* Now divide elements into two sets by comparing a rightmost set bit
of xor1 with the bit at the same position in each element.
Also, get XORs of two sets. The two XORs are the output elements.
The following two for loops serve the purpose */
for (i = 0; i < n; i++) {
if (arr[i] & set_bit_no)
/* arr[i] belongs to first set */
x = x ^ arr[i];
else
/* arr[i] belongs to second set */
y = y ^ arr[i];
}
for (i = 1; i <= n; i++) {
if (i & set_bit_no)
/* i belongs to first set */
x = x ^ i;
else
/* i belongs to second set */
y = y ^ i;
}
// NB! numbers can be swapped, maybe do a check ?
int x_count = 0;
for (int i=0; i<n; i++) {
if (arr[i]==x)
x_count++;
}
if (x_count==0)
return {y, x};
return {x, y};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment