The Reverse a String Interview Question
July 24th, 2010
A very common interview questions at technology companies like Microsoft and Google is, “Write a function which reverse a string.” It’s a very simple question but because there are so many different solutions, the hiring manager can tell a lot about a job candidate by exactly how the candidate answers the question. Reversing a string depends to a large extent on what language you use. For example, if you use C/C++ you will almost certainly use a pointer approach. If you use JavaScript, you’ll almost certainly use array-indexing. Let’s assume you’re using C/C++. One simple algorithm is to place one pointer at the start of the string, and place a second pointer at the end of the string (just before the ‘\0′ terminator). Then, in a loop, swap the characters pointed to by your two pointers, increment the front pointer, and decrement the back pointer. Loop while the front pointer is less than the back pointer. An interesting side note is that you can perform the swap operation in the usual way by using a temp char:
char temp = *front;
*front = *back;
*back = temp;
But you can also do a tricky in-place swap using the xor operator:
*front = *front ^ *back;
*back = *back ^ *front;
*front = *front ^ *back;
As always, a key to success is to articulate your answer (no matter what your approach) so that the interviewer knows the boundaries of your knowledge and can determine if you are a good match for the job he has open.
Entry Filed under: Interviewing
Trackback this post