Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
We can find mid if a[mid]<p and a[mid]>0 return mid;
else if a[mid]>p search left between 0 and mid else find between mid and p.
this is log(n) where n is length of array.
to ra1: since the constrain is 0 < k < p. there is no such k in your example. With the constrain, binary search works.
well the binary search work just as it is..because, if K is greater than current mid then their must be an element on right of current mid which is equal to K otherwise the last element cannot be p (which is greater than K). Similarly if K is less than current mid there must be an element on left of current mid equal to K (otherwise the current mid cannot be greater than K). So apply binary search as follows:
if K is greater than current mid, compare K with mid element of right array and vice versa.
well , skip k - a[i] elements after each element and then search again ....
- Anonymous June 10, 2012repeat till you find k