Reverse a string preserving spaces

Last Updated : 13 Jun, 2026

Given a string s, reverse the string without altering the positions of the spaces.

Examples: 

Input "Help others"
Output: sreh topleH
Explanation : Reversing the characters without spaces "srehtopleH" and inserting space at original place"sreh topleH"

Input: "internship at geeks for geeks"
Output: skeegrofsk ee gtapi hsn retni
Explanation : Reversing the characters without spaces "skeegrofskeegtapihsnretni" and inserting space at original place"skeegrofsk ee gtapi hsn retni"

Input : "abc de"
Output: edc ba
Explanation : Reversing the characters without spaces "edcba" and inserting space at original place"edc ba"

Try It Yourself
redirect icon

[Naive Approach] - Using a new String - O(n) Time and O(n) Space

The idea is to create a string to store results. Mark the space position of the given string in this string and then start Inserting the character from the input string into the result string in reverse order.
While inserting the character check if the result string already has a space at index ‘j’ or not. If it does, we copy the character to the next position.

C++
#include <iostream>
using namespace std;

string reverses(string &str)
{
    // Mark spaces in result
    int n = str.size();
    string result(n, '\0');
    for (int i = 0; i < n; i++)
        if (str[i] == ' ')
            result[i] = ' ';

    // Traverse input string from beginning
    // and put characters in result from end
    int j = n - 1;
    for (int i = 0; i < str.length(); i++) {
        
        // Ignore spaces in input string
        if (str[i] != ' ') {
            
            // ignore spaces in result.
            while(result[j] == ' ')
                j--;

            result[j] = str[i];
            j--;
        }
    }
    return result;
}

int main()
{
    string s = "internship at geeks for geeks";
    cout << reverses(s) << endl;
    return 0;
}
Java
import java.util.*;

public class Main {
    
    // Mark spaces in result
    public static String reverses(String str) {
        int n = str.length();
        char[] result = new char[n];
        Arrays.fill(result, '\0');
        for (int i = 0; i < n; i++)
            if (str.charAt(i) ==' ') result[i] = ' ';

        // Traverse input string from beginning
        // and put characters in result from end
        int j = n - 1;
        for (int i = 0; i < str.length(); i++) {
            
            // Ignore spaces in input string
            if (str.charAt(i) != ' ') {
                
                // ignore spaces in result.
                while(result[j] == ' ') j--;
                result[j] = str.charAt(i);
                j--;
            }
        }
        return new String(result);
    }

    public static void main(String[] args) {
        String s = "internship at geeks for geeks";
        System.out.println(reverses(s));
    }
}
Python
"""
Mark spaces in result
"""
def reverses(str):
    n = len(str)
    result = ['\0'] * n
    for i in range(n):
        if str[i] == ' ':
            result[i] = ' '
            
    # Traverse input string from beginning
    # and put characters in result from end
    j = n - 1
    for i in range(len(str)):
        
        # Ignore spaces in input string
        if str[i] != ' ':
            
            # ignore spaces in result.
            while result[j] == ' ':
                j -= 1
            result[j] = str[i]
            j -= 1
    return ''.join(result)

if __name__ == '__main__':
    s = "internship at geeks for geeks"
    print(reverses(s))

Output
skeegrofsk ee gtapi hsn retni

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

The idea is to use two pointers pointing at start and end of the string. If character at start or end is space, we move the pointer pointing to the space to the next position and swap only if both pointer point to a character.

C++
#include <iostream>
using namespace std;

string reverses(string &str)
{
    int n = str.length();

    // Initialize two pointers as two corners
    int start = 0;
    int end = n - 1;

    // Move both pointers toward each other
    while (start < end) {

        // If character at start or end is space,
        // ignore it
        if (str[start] == ' ') {
            start++;
            continue;
        }
        else if (str[end] == ' ') {
            end--;
            continue;
        }

        // If both are not spaces, do swap
        else {
            swap(str[start], str[end]);
            start++;
            end--;
        }
    }
    return str;
}

int main()
{
    string s = "internship at geeks for geeks";
    cout << reverses(s);
    return 0;
}
Java
import java.io.*;
import java.util.*;

class GFG{
    
public static String reverses(String str)
{
    int n = str.length();
 
    // Initialize two pointers as two corners
    int start = 0;
    int end = n - 1;
    
    char[] Str = str.toCharArray();
    
    // Move both pointers toward each other
    while (start < end)
    {
        
        // If character at start or end 
        // is space, ignore it
        if (Str[start] == ' ') 
        {
            start++;
            continue;
        }
        else if (Str[end] == ' ') 
        {
            end--;
            continue;
        }
 
        // If both are not spaces, do swap
        else 
        {
            char temp = Str[start];
            Str[start] = Str[end];
            Str[end] = temp;
            start++;
            end--;
        }
    }
    return String.valueOf(Str);
}

public static void main(String[] args) 
{
    String s = "internship at geeks for geeks";
    System.out.println(reverses(s));
}
}
Python
def reverses(Str):
  
    n = len(Str)
    Str = list(Str)

    # Initialize two pointers 
    # as two corners 
    start = 0
    end = n - 1

    # Move both pointers 
    # toward each other 
    while(start < end):

        # If character at start 
        # or end is space, 
        # ignore it 
        if(Str[start] == ' '):
            start += 1
            continue
        elif(Str[end] == ' '):
            end -= 1
            continue
            
        # If both are not 
        # spaces, do swap 
        else:
            Str[start], Str[end] = (Str[end],
                                    Str[start])
            start += 1
            end -= 1 
    return (''.join(Str))

s = "internship at geeks for geeks"
print(reverses(s)); 
C#
using System;
using System.Collections.Generic; 

class GfG{
    
static string reverses(string str)
{
    int n = str.Length;
    
    // Initialize two pointers 
    // as two corners
    int start = 0;
    int end = n - 1;
     
    char[] Str = str.ToCharArray();
     
    // Move both pointers toward 
    // each other
    while (start < end)
    {
        
        // If character at start or 
        // end is space, ignore it
        if (Str[start] == ' ') 
        {
            start++;
            continue;
        }
        else if (Str[end] == ' ') 
        {
            end--;
            continue;
        }
  
        // If both are not spaces, do swap
        else
        {
            char temp = Str[start];
            Str[start] = Str[end];
            Str[end] = temp;
            start++;
            end--;
        }
    }
    return new string(Str);
}
  
static void Main()
{
    string s = "internship at geeks for geeks";
 
    Console.Write(reverses(s));
}
}
JavaScript
function reverses(str)
    {
        let n = str.length;

        // Initialize two pointers
        // as two corners
        let start = 0;
        let end = n - 1;

        let Str = str.split('');

        // Move both pointers toward
        // each other
        while (start < end)
        {

            // If character at start or
            // end is space, ignore it
            if (Str[start] == ' ')
            {
                start++;
                continue;
            }
            else if (Str[end] == ' ')
            {
                end--;
                continue;
            }

            // If both are not spaces, do swap
            else
            {
                let temp = Str[start];
                Str[start] = Str[end];
                Str[end] = temp;
                start++;
                end--;
            }
        }
        return Str.join("");
    }
    
    let s = "internship at geeks for geeks";
    console.log(reverses(s));

Output
skeegrofsk ee gtapi hsn retni
Comment