Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
The way I understand this we are given an array. The positions at which there is no bunny will be set to 0. The position where there is a bunny will be set to 1. For example in the array {0,0,1,1,0,0,0,1,0,1,1,0,0} there are 5 bunnies at positions 2,3,7,9,10.
So given a position of a bunny, we need to know how many times the bunny can hop.
The first question to ask is when can the bunny stop hopping? This should happen when the bunny reaches either end of the array(0 or Length-1).
Another case when the bunny has to stop hopping is when the next position it can hop to is already occupied.
We can write a few functions to accomplish this
//MinPos = 0 initially, CurrentPos is the position of the bunny we are interested in. EndPos is L-1 where L is the length of the array.
int ValidHops(int arr[],int MinPos,int CurrentPos,int EndPos)
{
return LeftHops(arr,MinPos,CurrentPos) + RightHops(arr,CurrentPos,EndPos);
}
//find the position of the next bunny
//calculate position after jumping over it.
//terminate when the final position is either>=high or its occupied.
int RightHops(int arr[],int StartPos,int MaxPos)
{
//we know that StartPos is occupied
if (StartPos>=MaxPos) return 0;
//find the next bunny
for(int i=StartPos+1; ((i<=MaxPos)&&(arr[i]!=1));i++);
if (i==MaxPos) return 0; //no more valid hops if reached the end
int nextPos = 2*i-StartPos;
if (nextPos>MaxPos) return 0; //reached the right end of the array
if (arr[nextPos]==1) return 0; //the next position is occupied therefore cannot proceed further
return 1+RightHops(arr,nextPos,MaxPos);
}
int LeftHops(int arr[],int StartPos,int MinPos)
{
//we know that StartPos is occupied
if (StartPos<=MinPos) return 0;
//find the next bunny
for(int i=StartPos-1; ((i>=MinPos)&&(arr[i]!=1));i--);
if (i==MinPos) return 0; //no more valid hops if reached the end
int nextPos = 2*i-StartPos;
if (nextPos<MinPos) return 0; //reached the right end of the array
if (arr[nextPos]==1) return 0; //the next position is occupied therefore cannot proceed further
return 1+ LeftHops(arr,nextPos,MinPos);
}
Shouldn't the condition be a[i] ==1 , as we are checking that where is the next bunny. Given that in an array we assume that if there is a bunny its position is marked as 1.
Should the hopping happen only in 1 direction or it can happen in both directions?
- Naveen Reddy Mandadi April 05, 2012Should a position which is already hopped to can be hopped again, otherwise there can be infinite number of hops?