Amazon Interview Question
Developer Program EngineersCountry: United States
Interview Type: Phone Interview
Saurav:
A few minor things but I think you should hash the strings and count them that way, so you can differentiate the different compared strings. like 'test', 'string', 'small' would have a count associated with it. Rather than returning an arbitrary number. Also I think compareTo = arr[k] + " "; should be something more along the lines of:
compareTo += arr[k];
if(k < arr. length())
compareTo+= " ";
Also you should not set j=0 at the end of the first while but set j=3...
And your if(B.indexOf(compareTo) != -1) { counter++; } should be a while loop because it only returns the first occurrence and not the total... Therefore you need to have a separate index to iterate along B.
A lot of this would be understood if you could write out your thought process rather than just coding without any comments.
This is what my code looks like
- Saurav April 12, 2012public int countCommon(String A, String B)
{
int counter =0;
int j=3; int i=0;
String[] arr = A.split(" ");
while(i<arr.length){
while((i+j)<arr.length){
String compareTo="";
for(int k=i;k<(i+j);k++){
compareTo = arr[k] + " ";
}
if(B.indexOf(compareTo)!= -1){
counter++;
}
j++;
}
i++;
j=0;
}
return counter;
}