![]() |
VOOZH | about |
Write a program to reverse the order of words in a given sentence. A word is defined as a sequence of non-space characters. The sentence is a collection of words separated by spaces.
Examples:
Input: "Hello World"
Output: "World Hello"Input: "Programming is fun"
Output: "fun is Programming"
Approach: To solve the problem, follow the below idea:
The problem can be solved by splitting the sentence into words. After splitting the sentence into words, reverse the order of the words and then reconstruct the sentence by appending all the words with a space between them.
Below is the implementation of the algorithm:
fun is Programming
Time Complexity: O(N), where N is the length of the sentence.
Auxiliary Space: O(N), additional space is used for storing words.