GATE CSE
First time here? Checkout the FAQ!
x
+1 vote
181 views
Given a sorted array of distinct interger A[1...N] , you want to find out whether there is an index "i" for which A[i] =i . if this problem is solved using divide and conquer method,then find time complexity.
asked in Algorithms by Veteran (22.7k points)  
retagged by | 181 views

1 Answer

+3 votes

We can use modification of binary search here :

Basically we have to find index i such that a[i] = i in other a[i] - i = 0.

Now as the array is sorted , so all the indices j which is less than i will satisfy the property : a[j] - j <= 0 as the array is sorted so a[j] will be at least 1 less than a[i] and left index will also be at least 1 less than i hence the conclusion.

Similarly to the right of the ith index element , we have a[j] - j >= 0 .

So the key idea is just we find :

mid = left + right / 2 where left and right are the boundary indices and then check whether mid is the ith index we are looking for using the above mentioned property.For this we compare only its immediate left and right neighbours.

If it satisfies , well and good and we will report our final answer which is index i as mid only else we apply binary search recursively like normal one.

So time complexity remains the same i.e. O(logn)

Reference : http://stackoverflow.com/questions/4101141/algorithm-to-find-if-there-is-any-i-so-that-arrayi-equals-i

answered by Veteran (66.3k points)  
can u give solution for :
0,1,2,3,4,5,7,8,9,10,11,12

Here all will satisfy the given property but the problem says we need to report any such element.There may be more than 1 such elements in the array.But we are interested to find any one of them only.

As the problem says :

you want to find out whether there is an index "i" for which A[i] =i 

So even finding one such index will do..And remember this solution assumes that no duplicate elements should be there.

In this scenario hence we require O(logn) time only. 

not all A[6] there is 7...  so 7-6 >0 so we will go right end rt??
Yes this will correspond to best case..Hence O(1) for your input instance.


Top Users May 2017
  1. akash.dinkar12

    3548 Points

  2. pawan kumarln

    2126 Points

  3. Bikram

    1922 Points

  4. sh!va

    1682 Points

  5. Arjun

    1622 Points

  6. Devshree Dubey

    1272 Points

  7. Debashish Deka

    1270 Points

  8. Angkit

    1056 Points

  9. LeenSharma

    1028 Points

  10. Arnab Bhadra

    812 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 May 22 - 28
  1. Bikram

    1008 Points

  2. pawan kumarln

    752 Points

  3. Arnab Bhadra

    726 Points

  4. akash.dinkar12

    428 Points

  5. Arjun

    350 Points


22,896 questions
29,206 answers
65,329 comments
27,708 users