Expedia Interview Question
Software Engineer / Developersthe above algthm takes O(n) which is not good.
it didn't take advantage that the original array is sorted. The best sln will take O(lgN)
int find_rotation(int arr[],int size)
{
int index = 1;
if (size < 2) return 0;
if(arr[0] < arr[size-1]) return 0;
if ((arr[0] < arr[size/2])
{
return find_rotation(&arr[size/2],size/2)
}
else
{
return size/2 + find_rotation(arr,size/2)
}
}
Here is the code without recursion. I tried for couple of inputs and it seems to work. Plz let me know if someone finds a bug in it..
#include<stdio.h>
void main()
{
int i, a[100],n,start,mid,end,count=0;
printf("Enter the total no. of elements in the array \n");
scanf("%d", &n);
printf("Enter the elements in the rotated array \n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
start = 0;
end = n-1;
while(start != end)
{
mid = start+(end-start+1)/2;
if(a[start] < a[mid])
start = mid;
else
{
count = mid;
end = mid-1;
}
}
printf("The rotation count is %d \n", (count)?n-count:0);
}
When duplicate is allowed. The above algorithm does not work.
Say a[] = { 1, 2, 2, 2, 2, 2, 2, 2, 3}
a2[] = { 2, 2, 2, 2, 2, 2, 3, 1, 2}
If all the elements are equal then there cannot be a unique solution. Otherwise we can simply use binary search kind of technique to solve the problem in O(logn). The problem can be rephrased as find the least index in the given array such that arr[index]<arr[0].
The answer will be n-index. index is 0 based!. I suppose it is very easy to solve the new problem I phrased.
#include<iostream>
using namespace std;
#define SIZE 9
int rotation(int a[], int low, int high)
{
int mid;
mid = (low+high)/2;
if (a[low] <= a[mid])
{
return rotation(a, mid, high);
}
else
{
return low;
}
}
int main()
{
int a[] = {2, 2, 2, 2, 2, 2, 3, 1, 2};
int result = rotation(a, 0, SIZE - 1);
cout<<result<<endl;
system("PAUSE");
return 0;
}
Worst Case Complexity O(logn)
compare successive elements of array.. if a[i]<=a[i+1] proceed
- Anonymous May 22, 2007else /*a[i] > a[i+1] */
stop here u have find the point from where the array should actually start. now return the rotation..i think u can compute that