Reverse Words in a Sentence
Explore how to reverse the order of words in a sentence without changing the order of letters within each word. This lesson teaches an in-place method that involves reversing the entire string and then each individual word, achieving linear time and constant space complexity.
We'll cover the following...
Statement
Given a sentence (an array of characters), reverse the order of its words without affecting the order of letters within a given word. All operations must be done in place.
Example
The “Hello World” string should be reversed as “World Hello”.
Here’s another example of reversing words in a sentence:
Sample input
"Hello world."
Expected output
"world. Hello"
Note: The order of letters in a word isn’t reversed.
Try it yourself
Solution
We will follow two steps:
- Reverse the string.
- Traverse the string and reverse each word in place.
Note: In each iteration, keep traversing till a white space or end of text occurs.
Let’s apply this solution to our example:
- Initial string is:
- “The quick brown fox jumped over the lazy dog.”.
- Reverse the string:
- “.god yzal eht revo depmuj xof nworb kciuq ehT”
- Reverse each word in-place:
- “dog. lazy the over jumped fox brown quick The”
Time complexity
The time complexity of this solution is linear, .
Space complexity
The space complexity of this solution is constant, .
Note: The solution reverses every word in place, that is, it does not require any extra space.