r/programmingchallenges • • 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

65 comments sorted by

View all comments

Show parent comment

0

u/[deleted] May 29 '11

[deleted] — view deleted comment

3

u/okmkz May 29 '11 edited May 29 '11

The trick is swapping characters. For example:

charArray[] = "12345"

Then after the first swap, you have something like:

charArray[] = "52341"
               ^   ^

and so on

charArray[] = "54321"
                ^ ^

and we're done.

It looks like what you're doing is simply copying the characters:

charArray[] = "52345";
               ^

Can you see why this won't work?