I came across a post How to find a duplicate element in an array of shuffled consecutive integers? but later realized that this fails for many input.
For ex:
arr[] = {601,602,603,604,605,605,606,607}
#include <stdio.h>
int main()
{
int arr[] = {2,3,4,5,5,7};
int i, dupe = 0;
for (i = 0; i < 6; i++) {
dupe = dupe ^ a[i] ^ i;
}
printf ("%d\n", dupe);
return 0;
}
How can I modify this code so that the duplicate element can be found for all the cases ?
From original question:
It basically says, that algorithm only works when you have consecutive integers, starting with 1, ending with some N.
If you want to modify it to more general case, you have to do following things:
Find minimum and maximum in array. Then calculate expected output (xor all integers between minimum and maximum). Then calculate xor of all elements in array. Then xor this two things and you get an output.