Published in


Reversing Words

String Manipulation Example

Given a String S, reverse the string without reversing its individual words. Words are separated by dots.

Example 1:

S =
After reversing the whole
string(not individual words), the input
string becomes

Example 2:

S = pqr.mno
Output: mno.pqr
After reversing the whole
string , the input string becomes

Your Task:
You don't need to read input or print anything. Complete the function reverseWords() which takes string S as input parameter and returns a string containing the words in reversed order. Each word in the returning string should also be separated by ‘.’

Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)

1 <= |S| <= 2000

Approach :

  1. Having O(|s|) space complexity & O(|s|) time complexity where |s| is the length of the given string

class Solution
//Function to reverse words in a given string.
string reverseWords(string s)
string str="";
string result = "";
string word;

1 for(int i=0;s[i]!='\0';i++)
2 if(s[i]=='.')
3 word = s[i]+str;
4 str="";
5 else
6 str+=s[i];
7 result = word+result;
8 word="";
9 if(str!="")
10 result = str+result;
11 return result;
Below I will dry run an input to help you understand better.
You can infer from the above code using the numbers which have been marked and can easily understand how this question has been solved.

I am simply adding the dots before the word, like for eg above I made the word as .pqr and then appended it with the later word. So using this logic it becomes easy to get the desired output.

Link for the question:

Hope it helps! Keep coding!

Since you enjoyed reading my blog , why not buy me a coffee and supoort my work here!!

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store