Ali Shahid
Ali Shahid

Reputation: 516

Design and Analysis of Algorithm

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

Upvotes: 0

Views: 605

Answers (3)

Helium
Helium

Reputation: 368

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.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

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.

Upvotes: 0

taskinoor
taskinoor

Reputation: 46027

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

Upvotes: 2

Related Questions