Wednesday, September 21, 2011

Amazon interview question: you have unsorted array[n] elements. the numbers in the array[n] occurs event times except one number occurs odd time. So, write an algorithm to find that number. Also explain its complexity too. (time and space) both. (On ALGORITHM)"


Logic: Do Xor on the elements.
public class MainClass {
public static void main(String [] args)
{
int []a = new int []{1,1,2,3,2,4,4,4,4,1,1,5,6,5,1,6,1};
int res =a[0];
for(int i =1 ; i<a.length; i++)
{
res = res^a[i];
}
System.out.println(res);

}
}

1 comment: