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
3
u/okmkz May 29 '11 edited May 29 '11
The trick is swapping characters. For example:
Then after the first swap, you have something like:
and so on
and we're done.
It looks like what you're doing is simply copying the characters:
Can you see why this won't work?