## Google Interview Question

Software Engineer / DevelopersCode is correct only if n = pow ( 2, i) - 1

if n == 4 for example

list will be,

001

010

011

100

Xoring will not work in the case, the last bit occurances is 1

@binu

How can we identify the value of A[i] with just log(A[i]) operations ?For example if the input is 7 ie. 111 I need 3 read operations to identify that I have read 7. but 3 is greater than log7

You can read only one bit in one read operation. What I meant was, number of read operations required to read a number n, is a linear function of log(n).

If log(n) is integer, then number of operations = log(n)+1.

If log(n) is not an integer, then number of operations = ceil(log(n)), where ceil(x) = smallest integer greater than x. log(n) is of course base 2 logarithm of n.

Sorry for not explaining it earlier.

we can find the missing number by counting the number of bits set at each bit position for all the n-1 numbers. i.e add up numbers of bits set at bit 0 of all numbers. and Do the same for bit1, bit2 etc.

If n is a power of 2 , it will be easier to arrive at a solution. If not then we need bit more logic to calculate it. Run through with sample input to know what i mean.

Let C = Xor of all the elements from 1 to n. O(n) time. Let C' = Xor of the elements read in....let each element have t bits (on average) . So, time taken = n*t*n. Let A = missing no. C = A XOR C'. So, A = C XOR C'.

This procedure works for the case in which there is only one number missing. What if there are more than two numbers missing?

For solving the above algorithm we will need to use the concept of xor we will xor all the array elements and also xor all the numbers from 1 to n and finally xor both the xor of arrays and numbers together.

Implementation:

```
int findmissing(int arr[], int n){
int xor_number = 1;
int xor_array = arr[0];
for(int i = 2; i <= n + 1; i++)
xor_number = xor_number ^ i;
for(int i = 1; i < n; i++)
xor_array = xor_array ^ arr[i];
return xor_array ^ xor_number;
```

This is in the CareerCup Cracking the Coding interview and the solution is fairly clever.

ith bit of missing element would be :

zor of ith bit of all element in list and ith bit of 1 to n. So all duplicates will be nullified and missing elements bit will remain. Here is the quick code(may be buggy :))

result[i] will be a 32 bit array having missing element. Hope it helps.

- Gaurav September 03, 2011