Open In App

Java Program To Reverse Words In A Given String

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
4 Likes
Like
Report

Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i"

reverse-words

Examples

Input: s = "geeks quiz practice code" 
Output: s = "code practice quiz geeks"

Input: s = "getting good at coding needs a lot of practice" 
Output: s = "practice of lot a needs coding at good getting"

Algorithm:  

  • Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be "i ekil siht margorp yrev hcum".
  • Reverse the whole string from start to end to get the desired output "much very program this like i" in the above example.

Below is the implementation of the above approach: 

Output

much very program this like i

Time complexity: O(n)

Auxiliary Space: O(n)


Another Approach:

we can do the above task by splitting and saving the string in a reverse manner. 

Below is the implementation of the above approach:

Output:

Reversed String:
much very program this like i

Time Complexity: O(n) 

Auxiliary Space: O(n) for array s

Without using any extra space:
The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too.   

Below is the implementation of the above approach:

Output:

practice of lot a needs coding at good getting

Time complexity: O(n)

Auxiliary Space: O(n)

Please refer complete article on Reverse words in a given string for more details!


Similar Reads