Amazon Interview Question
Software Engineer / Developerstake the xor for 1 to n-1.....lets say x=(1^2^....^n-1)
now xor x with all elements from 1 to n in the array...
the result is the required no...
sum all the numbers
subtract the sum of n-1 numbers from the above sum
u get the duplicate
How does adding the numbers help? Are you confusing the qus with the "one is missing" problem?
((n-1) +1)/2 is the average value of the "proper" array.
Average * (n - 1) is the sum of 1..(n - 1).
Sum the elements in the array. The difference between these two sums is the extra.
Example:
1,2,3,3,4 (n = 5)
average = 2.5; sum = 10
sum of the given array is 13.
13 - 10 = 3, the extra value.
The indexing method works, but using math takes constant memory, instead of linear.
One of the best algorithms to solve the above problem statement is to use the concept of bit manipulation, we will first xor all the numbers from 1 to n - 1 and we will then xor all the array elements and store them in a separate variable and at the end, we will xor both of them together and finally we will get the duplicate element in the array.
Implementation:
int findrepeating(int arr[], int n){
int xor_numbers = 1;
int xor_array = arr[0];
for(int i = 2; i <= n - 1; i++)
xor_numbers = xor_numbers ^ i;
for(int i = 1; i < n; i++)
xor_array = xor_array ^ arr[i];
return xor_numbers ^ xor_array;
}
Check whether A[i] is already put into into A[A[i]].
- Silence February 04, 2010If yes -> duplicate.
If no, swap(A[i], A[A[i]])