Take the 2-minute tour ×

I am stuck in a problem, I need to solve a problem, here it is:

Write an Algorithm that finds an Index i in an array such that A[i] = i when 0<=i<=n-1, if no such index found return -1

I did this question in O(n) time but my fellows say that it can be done in less time some where near O(lg(n))

Can anyone helps me finding a better solution?? If so, Kindly reply to this post.. Thanks

share|improve this question
Think recursion and O(log(n)). –  duffymo May 18 '12 at 11:19
Is your array sorted? –  Rowland Shaw May 18 '12 at 11:19
Why don't you simply ask your fellow how this is going to work? –  Ingo May 18 '12 at 11:19
Same question, but on sorted array: stackoverflow.com/questions/4172580/… –  phoxis May 18 '12 at 11:27
add comment

3 Answers

up vote 2 down vote accepted

If the array is sorted then you can search that in O(lg(n)) using binary search. Otherwise it will require O(n).

share|improve this answer
add comment

You are supposed to do a binary search on the array. You missed a very important part of the problem statement - the array should be sorted in advance.

share|improve this answer
Array is already sorted in an increasing order. –  ChampTaurus May 18 '12 at 11:52
That is just what I said - simply pointed out you are missing an important bit of the statement. If the array is not sorted you can not improve the linear complexity. –  Ivaylo Strandjev May 18 '12 at 11:55
add comment

If the array is not sorted, this is impossible. I assume you are looking for a deterministic, non-probabilistic algorithm. Assume an algorithm "Alg" exists which solves the problem by visiting O(log(n)) cells of the array. Let V(I) be the set of cells that are visited by Alg on a given input I. Also assume the answer to an input I1 is -1 and Alg returns -1 correctly. Now change one of the cells of I1 that is not in V(I1) and give it to Alg again. For sure, Alg returns -1 again, which is not the correct answer.

share|improve this answer
add comment

Your Answer


