Reverse the ordering of words in a string

Arnkrishn picture Arnkrishn · Jun 17, 2009 · Viewed 191.9k times · Source

I have this string s1 = "My name is X Y Z" and I want to reverse the order of the words so that s1 = "Z Y X is name My".

I can do it using an additional array. I thought hard but is it possible to do it inplace (without using additional data structures) and with the time complexity being O(n)?

Answer

Bill the Lizard picture Bill the Lizard · Jun 17, 2009

Reverse the entire string, then reverse the letters of each individual word.

After the first pass the string will be

s1 = "Z Y X si eman yM"

and after the second pass it will be

s1 = "Z Y X is name My"