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)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Reverse individual words
- Replace all occurrences of string AB with C without using extra space
- Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
- Check if the characters in a string form a Palindrome in O(1) extra space
- Clone a stack without extra space
- Remove duplicates from a string in O(1) extra space
- Count words that appear exactly two times in an array of words
- Check if the given string of words can be formed from words present in the dictionary
- Reverse words in a given String in Java
- Print words of a string in reverse order
- Reverse words in a given String in Python
- Reverse String according to the number of words
- Reverse middle words of a string
- Program to reverse words in a given string in C++
- Reverse words in a given string | Set 2
- Reverse words in a given string
- Reverse the Words of a String using Stack
- Reverse a string preserving space positions
- Remove extra spaces from a string
- Find one extra character in a string
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.