Tuesday, August 2, 2011

Given two arrays of numbers, find if each of the two arrays have the same set of ntegers ? Suggest an algo which can run faster than NlogN without extra space?

3 comments :

Aman Goyal said...

take a long long integer and set the bit according to the number u get in first array when u traverse it.

take the second array, traverse it, for each number c if the bit is already set, reset it, else set the corresponding bit.

and the end of these operations, check if the integer is zero, if not, arrays do not have the same set of numbers.

o(1) space and O(n+n) time

sreekar said...

As far as I understood the question,

This is the my answer:

1) Caluculate XOR of all the elements in Array1 as x1
2) Calulate XOR of all the elements in Array2 as x2
3) if (x1 xor x2) == 0 the the numbers are equal in both arrays.

Let me know if this solution is correct

TC : O(N)

SHAN said...

wrong...
array 1: 1 1 2 2 3 3
xor= 0;
array 2: 6 6 7 7 8 8
xor=0;
xor1=xor2 .. but ur answer is wrong..
this is one case. there r so many cases using xor.. use something else