Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
The original problem says " Given a sorted list ... "
I presume that the "list" here is just a loose semantics for an array, which is iterable randomly. If the input is nevertheless a LinkedList, then yes, you cannot use BS on it efficiently (though it is implementable).
This is the correct implementation. It's sort of a trick question because linear traversal is obvious but since it's semi sorted, binary search can cut the search down to O(long). please use better notation next time, instead of sidx and eidx use left and right... it makes the readability a lot easier.
In case of ascending order, just find the first element which is less than its previous element.
for (i=1; i<n; i++)
{
if (a[i] < a[i-1])
return i;
}
return 0; // in case when there is no rotation.
If the linked list is sorted in ascending order then find min in the array.
if the LL is sorted descending order find the maximum element.
we also have to take care of duplicate elements by using 2 pointers.
O(n) complexity.
The rotation of a string or list is just pushing the values as though they were in a circular list:
orig: 1 2 3 4 5 6 7
rotate: 5 6 7 1 2 3 4
orig: "water"
rotate: "terwa"
Another helpful hint when dealing with rotations of strings is if you concatenate the string to its self the original string will be included in the new string.
terwa + terwa = terWATERwa which contains the original as a substring.
The solution in normal JavaScript (can be quickly written on browser, and executed:-), and following Binary Search:
//returns the starting point of an array-segment
var minList = function(arr) {
var len = arr.length;
//checks whether the array-segment is sorted
if(arr[0] <= arr[len-1]) {
return arr[0]; //returns the min value in an array-segment
} else {
//else continue till you find a sorted array segment
var arr2 = arr.splice(arr.length/2);
var min1 = minList(arr);
var min2 = minList(arr2);
return Math.min(min1,min2);
}
};
public static int findStartPoint(int [] array){
int left=0;
int right=array.length-1;
while (left<=right){
int mid=(left+right)/2;
if (array[mid]<array[mid-1]){
return mid;
}
if (array[mid]<array[left]){
right=mid-1;
}else if (array[mid]>array[right]){
left=mid+1;
}else if (array[mid]>array[left]&&array[mid]<array[right]){
return 0;
}
}
return -1;
}
Hey folks. I think you are all missing a very important hint that the array is sorted and rotated by some K positions. In that case we should use the binary search principle to find the reset point, which will be the minimum element in the array. Below is the complete code to demonstarte this technique that runs in O(Log N) time:
}
- ashot madatyan May 13, 2012