0

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

4
  • Think recursion and O(log(n)). Commented May 18, 2012 at 11:19
  • 6
    Is your array sorted? Commented May 18, 2012 at 11:19
  • Why don't you simply ask your fellow how this is going to work? Commented May 18, 2012 at 11:19
  • Same question, but on sorted array: stackoverflow.com/questions/4172580/… Commented May 18, 2012 at 11:27

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.