Given an array of integers with size 2N+1 such that N elements appear
twice in arbitrary positions and 1 element appears only once.
Devise an algorithm to find the lonely element.
Ex : {1 2 4 5 1 4 2}
Answer : 5
Devise an algorithm to find the lonely element.
Ex : {1 2 4 5 1 4 2}
Answer : 5
Solution :
Note the properties of XOR :
Complexity :- A ^ A = 0
- 0 ^ A = A
- A ^ (B ^ C) = (A ^ B) ^ C
- Time : O(N)
- Space : O(1)
int lonely_element(int input[], int N){
int result=0, i=0;
for(i=0; i<N; i++)
return result;
for(i=0; i<N; i++)
result ^= input[i];
return result;
}
No comments:
Post a Comment