VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-words-in-a-given-string/

⇱ Reverse words in a string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse words in a string

Last Updated : 29 Oct, 2025

Given a string s, find a way to reverse the order of the words in the given string.

Note: string may contain leading or trailing dots(.) or multiple trailing dots(.) between two words. The returned string should only have a single dot(.) separating the words.

Examples:

Input: s = "i.like.this.program.very.much" 
Output: much.very.program.this.like.i
Explanation: The words in the input string are reversed while maintaining the dots as separators, resulting in "much.very.program.this.like.i".

Input: s = ”..geeks..for.geeks.” 
Output: geeks.for.geeks

Input: s = "...home......"
Output: home

[Naive Approach] Using Stack - O(n) Time and O(n) Space

Push all words separated by dots into a stack, then pop each word one by one and append it back to form the reversed string.


Output
geeks.for.geeks

[Expected Approach] Using Two Pointer - O(n) Time and O(1) Space

Reverse the entire string, then iterate through it to extract words separated by dots. Reverse each word individually and update the original string until the end is reached. Refer to the figure to understand better...



Output
geeks.for.geeks

[Alternate Approach] Using inbuilt library functions - O(n) Time and O(n) Space

We can efficiently solve this problem using built-in library functions like split to break the string into words, reverse to reverse the order of words, and stringstream (or equivalent functions) to reconstruct the final reversed string. This approach simplifies implementation and improves readability.


Output
geeks.for.geeks
Comment