Reverse a string preserving space positions
Last Updated :
06 Mar, 2025
Given a string s, the task is to reverse the given string while preserving the position of spaces.
Examples:
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"
Input "Help others"
Output: sreh topleH
Explanation : Reversing the characters without spaces "srehtopleH" and inserting space at original place"sreh topleH"
[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
public class GfG{
static void reverses(String str)
{
char[] inputArray = str.toCharArray();
char[] result = new char[inputArray.length];
// Mark spaces in result
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] == ' ') {
result[i] = ' ';
}
}
// Traverse input string from beginning
// and put characters in result from end
int j = result.length - 1;
for (int i = 0; i < inputArray.length; i++) {
// Ignore spaces in input string
if (inputArray[i] != ' ') {
// ignore spaces in result.
if (result[j] == ' ') {
j--;
}
result[j] = inputArray[i];
j--;
}
}
System.out.println(String.valueOf(result));
}
public static void main(String[] args)
{
String s = "internship at geeks for geeks";
reverses(s);
}
}
Python
def reverses(st):
# Mark spaces in result
n = len(st)
result = [0] * n
for i in range(n):
if (st[i] == ' '):
result[i] = ' '
# Traverse input string from beginning
# and put characters in result from end
j = n - 1
for i in range(len(st)):
# Ignore spaces in input string
if (st[i] != ' '):
# Ignore spaces in result.
if (result[j] == ' '):
j -= 1
result[j] = st[i]
j -= 1
return ''.join(result)
if __name__ == "__main__":
s = "internship at geeks for geeks"
print(reverses(s))
C#
using System;
class GfG {
// Function to reverse the string
// and preserve the space position
static void reverses(string str)
{
char[] inputArray = str.ToCharArray();
char[] result = new char[inputArray.Length];
// Mark spaces in result
for (int i = 0; i < inputArray.Length; i++) {
if (inputArray[i] == ' ') {
result[i] = ' ';
}
}
// Traverse input string from beginning
// and put characters in result from end
int j = result.Length - 1;
for (int i = 0; i < inputArray.Length; i++) {
// Ignore spaces in input string
if (inputArray[i] != ' ') {
// ignore spaces in result.
if (result[j] == ' ') {
j--;
}
result[j] = inputArray[i];
j--;
}
}
for (int i = 0; i < result.Length; i++)
Console.Write(result[i]);
}
public static void Main()
{
string s = "internship at geeks for geeks";
reverses(s);
}
}
JavaScript
function reverses(str)
{
let inputArray = str.split("");
let result = new Array(inputArray.length);
// Mark spaces in result
for (let i = 0; i < inputArray.length; i++) {
if (inputArray[i] == ' ') {
result[i] = ' ';
}
}
// Traverse input string from beginning
// and put characters in result from end
let j = result.length - 1;
for (let i = 0; i < inputArray.length; i++) {
// Ignore spaces in input string
if (inputArray[i] != ' ') {
// ignore spaces in result.
if (result[j] == ' ') {
j--;
}
result[j] = inputArray[i];
j--;
}
}
return (result).join("");
}
let s = "internship at geeks for geeks";
console.log(reverses(s));
Outputskeegrofsk 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 preserveSpace(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 << preserveSpace(s);
return 0;
}
Java
import java.io.*;
import java.util.*;
class GFG{
public static String preserveSpace(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(preserveSpace(s));
}
}
Python
def preserveSpace(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(preserveSpace(s));
C#
using System;
using System.Collections.Generic;
class GfG{
static string preserveSpace(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(preserveSpace(s));
}
}
JavaScript
function preserveSpace(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(preserveSpace(s));
Outputskeegrofsk ee gtapi hsn retni
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem