Reverse a string preserving spaces

Last Updated : 4 Jul, 2026

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

Examples: 

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

Input: s = "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 : s = "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.

initial_string_
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.Arrays;

public class GFG {

    // 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
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))
C#
using System;

class GFG {
    static string reverses(string str)
    {
        int n = str.Length;
        char[] result = new char[n];

        // Mark spaces in result
        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 < n; i++) {

            // Ignore spaces in input string
            if (str[i] != ' ') {

                // Ignore spaces in result
                while (result[j] == ' ')
                    j--;

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

        return new string(result);
    }

    static void Main()
    {
        string s = "internship at geeks for geeks";
        Console.WriteLine(reverses(s));
    }
}
JavaScript
function reverses(str)
{
    let n = str.length;
    let result = new Array(n).fill("\0");

    // Mark spaces in result
    for (let i = 0; i < n; i++) {
        if (str[i] === " ")
            result[i] = " ";
    }

    // Traverse input string from beginning
    // and put characters in result from end
    let j = n - 1;
    for (let i = 0; i < n; i++) {

        // Ignore spaces in input string
        if (str[i] !== " ") {

            // Ignore spaces in result
            while (result[j] === " ")
                j--;

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

    return result.join("");
}

// Driver code
let s = "internship at geeks for geeks";
console.log(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.

Let us understand with an example:
Input: "internship at geeks for geeks"

  • Initially, start points to 'i' and end points to 's'. Since both are non-space characters, they are swapped, and both pointers move inward.
  • Whenever either start or end encounters a space, that pointer is moved without performing any swap. This ensures that every space remains at its original position.
  • Whenever both pointers point to non-space characters, those characters are swapped. This gradually reverses all letters while skipping over spaces.
  • The process continues until start >= end, after which all non-space characters have been reversed while the spaces remain at their original indices.

Output: "skeegrofsk ee gtapi hsn retni"

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
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("");
    }
    
// Driver code
let s = "internship at geeks for geeks";
console.log(reverses(s));

Output
skeegrofsk ee gtapi hsn retni
Comment