![]() |
VOOZH | about |
Given an array A[] having n positive elements. The task to create another array B[] such as B[i] is XOR of all elements of array A[] except A[i].
Examples :
Input : A[] = {2, 1, 5, 9}
Output : B[] = {13, 14, 10, 6}
Input : A[] = {2, 1, 3, 6}
Output : B[] = {4, 7, 5, 0}
Naive Approach :
We can simple calculate B[i] as XOR of all elements of A[] except A[i], as
for (int i = 0; i < n; i++)
{
B[i] = 0;
for (int j = 0; j < n; j++)
if ( i != j)
B[i] ^= A[j];
}
Time complexity for this naive approach is O (n^2).
Auxiliary Space for this naive approach is O (n).
Optimized Approach :
First calculate XOR of all elements of array A[] say 'xor', and for each element of array A[] calculate A[i] = xor ^ A[i] .
int xor = 0; for (int i = 0; i < n; i++) xor ^= A[i]; for (int i = 0; i < n; i++) A[i] = xor ^ A[i];
Time complexity for this approach is O (n).
Auxiliary Space for this approach is O (1).
Output:
3 5 0 2 4
Time Complexity : O(n)
Auxiliary Space : O(1)
Related Problem :
A Product Array Puzzle