Given array A, check if A[i] = i for any i exists.
I'm supposed to solve this faster than linear time, which to me seems impossible. The solution I came up with is to first sort the array in n*log(n) time, and then you can easily check faster than linear time. However, since the array is given unsorted I can't see an "efficient" solution?
You can't have a correct algorithm with better than
O(N)
complexity for an arbitrary (unsorted) array.Suppose you have the solution better than
O(N)
. It means that the algorithm has to omit some items of the array since scanning all the items isO(N)
.Construct
A
such thatA[i] != i
for alli
then run the algorithm. LetA[k]
be the item which has been omitted. Assignk
toA[k]
, run the algorithm again - it'll returnno such items
whenk
is expected.