Thursday, July 9, 2009

Odd one out !!

Problem: In an array of integers, all but one occur even number of times. Find the one which occur odd number of times.

First solution:
Use Hashmap like data structure Map to hold the Integer in the given array & the corresponding count.
performance : O(n) + O(n) = O(n)
Problem : extra space & data structure

Second solution:
Sort the array & start skipping the pair e.g. [2,2,3,3,9,9,11,11,11,12,12,34,34] : 11 cannot be skipped as it’s not a pair.
performance: O (nlog(n)) + O(n)
problem: bad performance

Trick solution:
We know X XOR X = 0, therefore start with 0 as result and XOR all the elements with result.
performace : O(n)
problem: none, let me know if you see any


public static void main(String[] args){
int[] arr = {2,3,6,9,20,2,4,6,9,20,3};
int result = 0;
for(int i: arr){
result ^= i;
}
System.out.println(result); //prints 4
}




No comments: