Amazon Interview Question
InternsCountry: India
Interview Type: In-Person
This one is often asked / talked about:
blogs.msdn.com/b/bali_msft/archive/2009/02/03/search-for-a-number-in-shifted-sort-array-within-o-log-n-time.aspx
def searchB(arr, start, end, key):
length = len(arr)-1
if start>end:
end = length+end
while(start<end):
mid = (start+end)/2
if key == arr[start%length]:
return start%length
elif key == arr[end%length]:
return end%length
elif key == arr[mid%length]:
return mid%length
elif key>arr[mid%length]:
start = mid+1
else:
end = mid
return -1
public int searchB(arr, start, end, key)
{
length = arr.length-1;
if (start>end)
{
end = length+end;
}
while(start<end):
{
mid = (start+end)/2
if(key == arr[start%length])
{
return start%length;
}
else if (key == arr[end%length])
{
return end%length;
}
else if (key == arr[mid%length])
{
return mid%length;
}
else if (key>arr[mid%length])
{
start = mid+1;
}
else
{
end = mid;
}
}
return -1
}
public class CircularBinSearch {
private int[] arr;
private int offset;
public CircularBinSearch(int[] arr, int offset){
this.arr = arr;
this.offset = offset;
}
private int getValue(int index){
return this.arr[getWithOffset(index)];
}
private int getWithOffset(int index) {
return (index+offset)%this.arr.length;
}
public int search(int value){
int l = 0;
int r = arr.length;
int result = -1;
while(l<r){
int center = (l+r)/2;
int currValue = getValue(center);
if(currValue == value){
l = center;
break;
}
if(currValue<value){
l = center+1;
}else{
r = center - 1;
}
}
if(value == getValue(l)){
result = l;
}
return getWithOffset(result);
}
}
This is working code.
Please check it and give any comment if you have.
- Rahul October 02, 2013