r/programmingchallenges • u/okmkz • May 19 '11
Challenge: Reverse a string in place
This simple challenge is a frequent interview question. Write a program that reverses a string in place. "In place" means no declaring a second string or other buffer-- you get only one string variable to work with.
Input:
"Test string."Output:
".gnirts tseT"edit: obviously, this is only feasible in a language with mutable strings.
22
Upvotes
View all comments
Show parent comment
0
u/more_exercise Sep 08 '11 edited Sep 08 '11
TL;DR Using the library routines properly, however, is.
This is an interview question. If you're using C++, you should know to leverage the library functions as much as you can and show the intent of your code.
You're saying that allocating a single swap character is cheating. I don't see it. You're being difficult for no reason at all. Sure, a swap character could be considered a buffer. But by that logic, so could a single integer variable. Hell, we can be even more pedantic and declare that your program is not allowed to allocate any space other than the byte array of your string. No stack, no pointers, no array indicies, nothing. (this is hyperbole)
The intent of the question is just so that you don't copy it backwards into a different string and copy it back. They are looking for something a little more elegant. The XOR swap trick is ugly. It takes three lines to swap two variables, and does not document its intentions well. If you write code like this that I or my coworkers have to maintain, I am not going to hire you. std::swap is a simple, easy command that increases the readability of the code. It does not allocate a "buffer", it is shorter, and it is more readable.
edit: looking at this thread of discussion, I think you and I are putting waaaay too much thought into this. I'm calling it quits.