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”
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”
- 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:
much very program this like i
The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple space in between. Thanks to rka143 for providing this version.
Time Complexity: O(n)
we can do the above task by splitting and saving the string in reverse manner.
Reversed String: much very program this like i
Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Reverse middle words of a string
- Reverse String according to the number of words
- Program to reverse words in a given string in C++
- Reverse words in a given String in Python
- Reverse words in a given String in Java
- Print words of a string in reverse order
- Check if the given string of words can be formed from words present in the dictionary
- Reverse individual words
- Reverse individual words with O(1) extra space
- Create a new string by alternately combining the characters of two halves of the string in reverse
- Check if a given string is a Reverse Bitonic String or not
- Count words in a given string
- Shortest substring of a string containing all given words
- Minimum Distance Between Words of a String
- Check if given words are present in a string
- Print all funny words in a string
- Program to extract words from a given String
- Count words present in a string
- Remove Duplicate/Repeated words from String
- Check if a two character string can be made using given words