Given a string str, the task is to reverse all the individual words.
Input: str = “Hello World”
Output: olleH dlroW
Input: str = “Geeks for Geeks”
Output: skeeG rof skeeG
Approach: A solution to the above problem has been discussed in this post. It has a time complexity of O(n) and uses O(n) extra space. In this post, we will discuss a solution which uses O(1) extra space.
- Traverse through the string until we encounter a space.
- After encountering the space, we use two variables ‘start’ and ‘end’ pointing to the first and last character of the word and we reverse that particular word.
- Repeat the above steps until the last word.
Below is the implementation of the above approach:
skeeG rof skeeG
Time Complexity: O(n)
Auxiliary Space: O(1)
- Reverse individual words
- Clone a stack without extra space
- Replace all occurrences of string AB with C without using extra space
- Remove duplicates from a string in O(1) extra space
- Check if the characters in a string form a Palindrome in O(1) extra space
- Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
- Reverse words in a given string
- Reverse middle words of a string
- Reverse words in a given String in Java
- Reverse String according to the number of words
- Reverse words in a given String in Python
- Print words of a string in reverse order
- Reverse a string preserving space positions
- Check if the given string of words can be formed from words present in the dictionary
- Count words that appear exactly two times in an array of words
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.