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
Similar Reads
Reverse a String | Shell Programming In shell scripting, reversing a string can be done using various methods, such as rev, awk, sed, and Perl. Here, we provide examples of reversing a string using different approaches and commands in Unix/Linux systems. We are given a string and we have to use shell script to print it in the reverse o
4 min read
Print reverse string after removing vowels Given a string s, print reverse of string and remove the characters from the reversed string where there are vowels in the original string. Examples: Input : geeksforgeeksOutput : segrfsegExplanation :Reversed string is skeegrofskeeg, removing characters from indexes 1, 2, 6, 9 & 10 (0 based ind
13 min read
Remove spaces from a given string Given a string, remove all spaces from the string and return it. Input: "g eeks for ge eeks "Output: "geeksforgeeks"Input: "abc d "Output: "abcd"Expected time complexity is O(n) and only one traversal of string. Below is a Simple Solution 1) Iterate through all characters of given string, do followi
8 min read
Remove duplicates from a string in O(1) extra space Given a string str of lowercase characters, the task is to remove duplicates and return a resultant string without modifying the order of characters in the original string. Examples: Input: str = "geeksforgeeks" Output: geksfor Input: str = "characters" Output: chartes Approach: The idea is to use b
13 min read
Print reverse of a string using recursion Given a string, the task is to print the given string in reverse order using recursion.Examples:Input: s = "Geeks for Geeks"Output: "skeeG rof skeeG"Explanation: After reversing the input string we get "skeeG rof skeeG". Input: s = "Reverse a string Using Recursion"Output: "noisruceR gnisU gnirts a
5 min read
How to reverse a String in Python Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Letâs see how it works:Using string slicingThis slicing method is one of the s
4 min read