Move spaces to front of string in single traversal

Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once.

Examples:

Input  : str = "geeks for geeks"
Output : ste = "  geeksforgeeks"

Input  : str = "move these spaces to beginning"
Output : str = "    movethesespacestobeginning"
There were four space characters in input,
all of them should be shifted in front. 

Method 1 (Using Swap)
Idea is to maintain two indices i and j. Traverse from end to beginning. If the current index contains space, swap chars in index i with index j. This will bring all spaces to beginning of the array.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to bring all spaces in front of
// string using swapping technique
#include<bits/stdc++.h>
using namespace std;
  
// Function to find spaces and move to beginning
void moveSpaceInFront(char str[])
{
    // Traverse from end and swap spaces
    int i = strlen(str)-1;
    for (int j = i; j >= 0; j--)
        if (str[j] != ' ')
            swap(str[i--], str[j]);
}
  
// Driver code
int main()
{
    char str[] = "Hey there, it's GeeksforGeeks";
    moveSpaceInFront(str);
    cout << str;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to bring all spaces in front of 
// string using swapping technique 
class GFG 
{
  
    // Function to find spaces and move to beginning 
    static void moveSpaceInFront(char str[]) 
    
        // Traverse from end and swap spaces 
        int i = str.length-1
        for (int j = i; j >= 0; j--) 
            if (str[j] != ' ')
            {
                char c = str[i];
                str[i] = str[j];
                str[j] = c;
                i--;
            }
    }    
  
    // Driver code 
    public static void main(String[] args)
    {
        char str[] = "Hey there, it's GeeksforGeeks".toCharArray(); 
        moveSpaceInFront(str); 
        System.out.println(String.valueOf(str));
    }
}
  
// This code is contributed by 
// 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to bring all spaces 
# in front of string using swapping technique
  
# Function to find spaces and move to beginning
def moveSpaceInFront(s):
  
    # Traverse from end and swap spaces
    i = len(s) - 1;
    for j in range(i, -1, -1):
        if (s[j] != ' '):
            s = swap(s, i, j);
            i -= 1;
    return s;
      
def swap(c, i, j):
    c = list(c)
    c[i], c[j] = c[j], c[i]
    return ''.join(c) 
      
# Driver code
s = "Hey there, it's GeeksforGeeks";
s = moveSpaceInFront(s);
print(s);
  
# This code is contributed 
# by Princi Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to bring all spaces in front of 
// string using swapping technique 
using System;
  
class GFG 
{
  
    // Function to find spaces and move to beginning 
    static void moveSpaceInFront(char []str) 
    
          
        // Traverse from end and swap spaces 
        int i = str.Length-1; 
        for (int j = i; j >= 0; j--) 
            if (str[j] != ' ')
            {
                char c = str[i];
                str[i] = str[j];
                str[j] = c;
                i--;
            }
    
  
    // Driver code 
    public static void Main()
    {
        char []str = "Hey there, it's GeeksforGeeks".ToCharArray(); 
        moveSpaceInFront(str); 
        Console.WriteLine(String.Join("",str));
    }
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Output:

   Heythere,it'sGeeksforGeeks

Time complexity-: O(n)
Auxiliary Space-: O(1)

 

Method 2 (Without using swap)
The idea is to copy all non-space characters to end. Finally copy spaces.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to bring all spaces in front of
// string using swapping technique
#include<bits/stdc++.h>
using namespace std;
  
// Function to find spaces and move to beginning
void moveSpaceInFront(char str[])
{
     // Keep copying non-space characters
     int i = strlen(str);
     for (int j=i; j >= 0; j--)
          if (str[j] != ' ')
             str[i--] = str[j];
  
     // Move spaces to be beginning
     while (i >= 0)
         str[i--] = ' ';
}
  
// Driver code
int main()
{
    char str[] = "Hey there, it's GeeksforGeeks";
    moveSpaceInFront(str);
    cout << str;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to bring all spaces in front of
// string using swapping technique
class GFG 
{
  
// Function to find spaces and move to beginning
static void moveSpaceInFront(char str[])
{
    // Keep copying non-space characters
    int i = str.length-1;
      
    for (int j = i; j >= 0; j--)
        if (str[j] != ' ')
            str[i--] = str[j];
  
    // Move spaces to be beginning
    while (i >= 0)
        str[i--] = ' ';
}
  
// Driver code
public static void main(String[] args) 
{
    char str[] = "Hey there, it's GeeksforGeeks".toCharArray();
    moveSpaceInFront(str);
    System.out.println(String.valueOf(str));
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to bring all spaces 
# in front of sing using swapping technique
  
# Function to find spaces and 
# move to beginning
def moveSpaceInFront(s):
  
    # Keep copying non-space characters
    i = len(s) - 1;
      
    for j in range(i, -1, -1):
        if (s[j] != ' '):
            s = s[:i] + s[j] + s[i + 1:]
            i -= 1;
  
    # Move spaces to be beginning
    while (i >= 0):
        s = s[:i] + ' ' + s[i + 1:]
        i -= 1
    return s;
  
# Driver code
s = "Hey there, it's GeeksforGeeks";
s = moveSpaceInFront(s);
print(s);
  
# This code is contributed 
# by Princi Singh 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to bring all spaces in front of 
// string using swapping technique
using System;
  
class GFG 
  
// Function to find spaces and move to beginning 
static void moveSpaceInFront(char []str) 
    // Keep copying non-space characters 
    int i = str.Length-1; 
      
    for (int j = i; j >= 0; j--) 
        if (str[j] != ' '
            str[i--] = str[j]; 
  
    // Move spaces to be beginning 
    while (i >= 0) 
        str[i--] = ' '
  
// Driver code 
public static void Main(String[] args) 
    char []str = "Hey there, it's GeeksforGeeks".
                                    ToCharArray(); 
    moveSpaceInFront(str); 
    Console.WriteLine(String.Join("",str)); 
  
// This code is contributed by Rajput-Ji 

chevron_right


Output:

   Heythere,it'sGeeksforGeeks

Time complexity-: O(n)
Auxiliary Space -:O(1)

This article is contributed by SAKSHI TIWARI. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.