Related Articles

Related Articles

Reverse individual words with O(1) extra space
  • Difficulty Level : Easy
  • Last Updated : 08 Jul, 2019

Given a string str, the task is to reverse all the individual words.

Examples:

Input: str = “Hello World”
Output: olleH dlroW

Input: str = “Geeks for Geeks”
Output: skeeG rof skeeG

Approach: A solution to the above problem has been discussed in this post. It has a time complexity of O(n) and uses O(n) extra space. In this post, we will discuss a solution which uses O(1) extra space.



  • Traverse through the string until we encounter a space.
  • After encountering the space, we use two variables ‘start’ and ‘end’ pointing to the first and last character of the word and we reverse that particular word.
  • Repeat the above steps until the last word.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to resturn the string after
// reversing the individual words
string reverseWords(string str)
{
  
    // Pointer to the first character
    // of the first word
    int start = 0;
    for (int i = 0; i <= str.size(); i++) {
  
        // If the current word has ended
        if (str[i] == ' ' || i == str.size()) {
  
            // Pointer to the last character
            // of the current word
            int end = i - 1;
  
            // Reverse the current word
            while (start < end) {
                swap(str[start], str[end]);
                start++;
                end--;
            }
  
            // Pointer to the first character
            // of the next word
            start = i + 1;
        }
    }
  
    return str;
}
  
// Driver code
int main()
{
    string str = "Geeks for Geeks";
  
    cout << reverseWords(str);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach 
class GFG
{
    static String swap(String str, int i, int j) 
    
        StringBuilder sb = new StringBuilder(str); 
        sb.setCharAt(i, str.charAt(j)); 
        sb.setCharAt(j, str.charAt(i)); 
        return sb.toString(); 
    
      
    // Function to resturn the string after 
    // reversing the individual words 
    static String reverseWords(String str) 
    
      
        // Pointer to the first character 
        // of the first word 
        int start = 0
        for (int i = 0; i < str.length(); i++) 
        
      
            // If the current word has ended 
            if (str.charAt(i) == ' ' || 
                    i == str.length()-1 )
            {
      
                // Pointer to the last character 
                // of the current word 
                int end;
                if (i == str.length()-1)
                    end = i ;
                else
                    end = i - 1
                      
                // Reverse the current word 
                while (start < end)
                
                    str = swap(str,start,end) ;
                    start++; 
                    end--; 
                
      
                // Pointer to the first character 
                // of the next word 
                start = i + 1
            
        
      
        return str ; 
    
      
    // Driver code 
    public static void main(String args[])
    {
        String str = "Geeks for Geeks"
      
        System.out.println(reverseWords(str)); 
    }
}
  
// This code is contributed by AnkitRai01

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Function to resturn the after
# reversing the individual words
def reverseWords(Str):
  
    # Pointer to the first character
    # of the first word
      
    start = 0
    for i in range(len(Str)):
        # If the current word has ended
        if (Str[i] == ' ' or i == len(Str)-1):
  
            # Pointer to the last character
            # of the current word
            end = i - 1
            if(i == len(Str)-1):
                end = i
              
            # Reverse the current word
            while (start < end):
                Str[start], Str[end]=Str[end],Str[start]
                start+=1
                end-=1
              
  
            # Pointer to the first character
            # of the next word
            start = i + 1
          
    return "".join(Str)
  
# Driver code
Str = "Geeks for Geeks"
Str=[i for i in Str]
  
print(reverseWords(Str))
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach 
using System;
      
class GFG
{
  
    // Function to resturn the string after 
    // reversing the individual words 
    // Function to resturn the string after 
    // reversing the individual words 
    static String reverseWords(String str) 
    
      
        // Pointer to the first character 
        // of the first word 
        int start = 0; 
        for (int i = 0; i < str.Length; i++) 
        
      
            // If the current word has ended 
            if (str[i] == ' ' || 
                    i == str.Length-1 )
            {
      
                // Pointer to the last character 
                // of the current word 
                int end;
                if (i == str.Length-1)
                    end = i ;
                else
                    end = i - 1 ; 
                      
                // Reverse the current word 
                while (start < end)
                
                    str = swap(str,start,end) ;
                    start++; 
                    end--; 
                
      
                // Pointer to the first character 
                // of the next word 
                start = i + 1; 
            
        
      
        return str ; 
    }
      
    static String swap(String str, int i, int j) 
    
        char []ch = str.ToCharArray(); 
        char temp = ch[i]; 
        ch[i] = ch[j]; 
        ch[j] = temp; 
        return String.Join("",ch); 
    }
      
    // Driver code 
    public static void Main(String []args)
    {
        String str = "Geeks for Geeks"
      
        Console.WriteLine(reverseWords(str)); 
    }
}
  
/* This code is contributed by PrinciRaj1992 */

chevron_right


Output:

skeeG rof skeeG

Time Complexity: O(n)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :