Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Two pointer, one pointing to the top and one pointing the bottom. TopPtr moving downwards and BottomPtr moving upwards. Each time swap the char until TopPtr and BottomPtr meets. O(n/2)
Nice solution, but the complexity is O(n). The "/2" part doesn't matter when n is in the order of millions.
I think a follow up question to ask would be if there are any restrictions such as only reversing words etc. for example he may be asking to produce a result for a given input "what is your name" as "name your is what".
If this is the case I would split the string first into 2 dimensional array and then merge them back in reverse order.
Yes, but creating a linked list out of a string(char array) cannot be done in O(1). It takes O(n).. So your answer is not really relevant to the question asked.
There can be a better solution.
If you get to store the list in a doubly linked list, then you can reverse it in O(1).
You might understand what I said if you have studied Linked List from Thomas H Cormen's book. There is a problem there for reversing a linked list in O(1). The solution can apply here as well.
How would you return as a string?
Don't you have to use for loop to add each character in reversed linked list?
Yes, but creating the linked list is a O(n) operation. So no benefit in creating a linked list here.
String reverse (String inString) {
- soconfusedgrad October 31, 2012Char[] ret= inString.toCharArray();
int length = inString.length;
for (int i = 0; i < length/2; i++){
char temp = ret [length-1-i];
ret [length-1-i] = ret [i];
ret [i] = temp;
}
return ret.toString();
}
Complexity: O(N)