VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-reverse-order-of-words-in-a-sentence/

⇱ Program to reverse order of words in a sentence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to reverse order of words in a sentence

Last Updated : 18 Jan, 2024

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.

Step-by-step algorithm:

  • Split the sentence into words using space as the delimiter.
  • Reverse the order of the words.
  • Reconstruct the sentence by joining the reversed words with spaces.

Below is the implementation of the algorithm:


Output
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.

Comment
Article Tags:
Article Tags: