Interview question - Search in sorted array X for index i such that X[i] = i

algorithm, arrays, c++, java

Solution

This can be done in `O(logN)` time and `O(1)` space by using a slightly modified binary search.

Consider a new array `Y` such that `Y[i] = X[i] - i`

Array X : -3 -1   0  3  5  7
index   :  0  1   2  3  4  5
Array Y : -3 -2  -2  0  1  2

Since the elements in `X` are in increasing order, the elements in the new array `Y` will be in non-decreasing order. So a binary search for `0` in `Y` will give the answer.

But creating `Y` will take `O(N)` space and `O(N)` time. So instead of creating the new array you just modify the binary search such that a reference to `Y[i]` is replaced by `X[i] - i`.

Algorithm:

function (array X) 
       low  = 0
       high = (num of elements in X) - 1

       while(low <= high) 
               mid = (low + high) / 2

               // change X[mid] to X[mid] - mid
               if(X[mid] - mid == 0)
                       return mid

               // change here too
               else if(X[mid] - mid < 0)
                       low = mid + 1;

               else
                       high = mid - 1;
       end while

       return -1 // no such index exists...return an invalid index.

end function

Java implementation

C++ implementation

Problem

I was asked the following question in my interview yesterday: Consider a Java or C++ array say `X` which is sorted and no two elements in it are same. How best can you find an index say `i` such that element at that index is also `i`. That is `X[i] = i`. As clarification she also gave me an example: ``` Array X : -3 -1 0 3 5 7 index : 0 1 2 3 4 5 Answer is 3 as X[3] = 3. ``` The best I could think was a linear search. After the interview I though a lot on this problem but could not find any better solution. My argument is: the element with the required property can be anywhere in the array. So it could also be at the very end of the array so we need to check every element. I just wanted to confirm from the community here that I'm right. Please tell me I'm right :)

Original source