If we have an array of integers then how can we find the number of ways that they be XORed so that the result is 0 . Here at each step only one integer(i) can be decreased by any amount say d such that (i-d)>=0 . E.g for the integers 11,15,8 we can decrease 11 to 7 so that 7^15^8 =0 . Similary 15 can be reduced to 3 such that 11^3^8 = 0 and 8 can be reduced to 4 such that 11^15^4=0 . Hence total ways is 3
My approach: to this is for each integer , go on decreasing it and at each step XOR it with remaining integers in the array , if the result is 0 , break. Check this for all integers and get the total ways. But this is 0(n^2) . Is there any efficient way to do it?
Thanks.
You can XOR all integers in your array, then in loop XOR the result with each of your integers (it will “remove” that integer from all because
x^xis always 0). As a result you’ll get XOR of the other members and that’s the number to be replaced (becausex^xis always 0).In
b[i]you’ll get the number to be replaced witha[i]to get zero.I edited my answer and tried, it works. This is O(n).