Update appNew update is available. Click here to update.

Reverse Words In A String

Last Updated: 5 Sep, 2020
Difficulty: Easy


Try Problem

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.
Input Format :
The first line of input  contains a string that you need to reverse word by word.
Output Format :
Print the reversed string such that there should be only one space between two strings and there should not be any trailing space.
Note :
Do not print anything. It has already been taken care of.

If the string data type is immutable in your language, consider using a mutable data type as an alternative.
If the string data type is mutable in your language, can you solve it in place with O(1) extra space?
Constraints :
0 <= N <= 10^5

Time Limit: 1 sec

Approach 1

  • Create a String ans to store the reversed string.
  • Initialize a variable i to 0 and iterate the whole string through a while loop.
  • Skip initial spaces by just incrementing i.
  • Create a String that will store the current word.
  • Add the currentword and space at the beginning of ans.
  • After traversing the whole string, check if the length of ans is greater than 0 then return ans after removing the last space otherwise return an empty string.
Try Problem