VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-individual-words/

⇱ Reverse individual words - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse individual words

Last Updated : 17 Mar, 2025

Given string str, we need to print the reverse of individual words.

Examples:

Input: Hello World
Output: olleH dlroW
Explanation: Each word in "Hello World" is reversed individually, preserving the original order, resulting in "olleH dlroW".

Input: Geeks for Geeks
Output: skeeG rof skeeG

[Expected Approach] Stack-Based Word Reversal - O(n) Time and O(n) Space

We use a stack to store words character by character until we encounter a space. When a space is found, we pop and print the characters from the stack, effectively reversing the word. This process continues for all words in the string


Output
skeeG rof skeeG

[Alternate Approach] Using Inbulit Functions - O(n) Time and O(n) Space

To reverse individual words in a string, we can use built-in functions like stringstream in C++, StringBuilder in Java, split in Python and other languages. After splitting the string into words, we iterate over each word and reverse it using the reverse function.


Output
skeeG rof skeeG 

Related Article:


Comment