Update appNew update is available. Click here to update.

Reverse Words In A String

Contributed by
Anish De
Easy
yellow-spark
0/40
Avg time to solve 10 mins
Success Rate 90 %
Share
165 upvotes

Problem Statement

You are given a string of length N. You need to reverse the string word by word. There can be multiple spaces between two words and there can be leading or trailing spaces but in the output reversed string you need to put a single space between two words, and your reversed string should not contain leading or trailing spaces.

For example :

If the given input string is "  Welcome to   Coding  Ninjas", then you should return "Ninjas Coding to Welcome" as the reversed string has only a single space between two words and there is no leading or trailing space.
Detailed explanation ( Input/output format, Notes, Images )
Constraints :
1 <= T <= 50
0 <= N <= 10^5

Time Limit: 1 sec
Sample Input 1 :
2
Welcome   to Coding Ninjas
   I am   a    star
Sample Output 1:
Ninjas Coding to Welcome
star a am I
Explanation For Sample Input 1:
In the first test case, you need to reduce multiple spaces between two words to a single space in the reversed string and observe how the multiple spaces, leading and trailing spaces have been removed.

In the second test case, Your reversed string should not contain leading or trailing spaces.
Sample Input 2 :
1
Hello  World!!
Sample Output 2:
World!! Hello
Reset Code
Full screen
Auto
copy-code
Console