Write a program to reverse the given string while preserving the position of spaces.
Examples:
Input : "abc de"
Output : edc ba
Input : "intern at geeks"
Output : skeegt an retni
Input : "Help others"
Output : sreh topleH
- Create a string to store results. Mark the space position of the given string in this string.
- Insert the character from the input string into the result string in reverse order.
- While inserting the character check if the result string already contains a space at index ‘j’ or not. If it contains, we copy the character to the next position.
Below is the implementation of the above steps.
C++
#include <iostream>
using namespace std;
string reverses(string str)
{
int n = str.size();
string result(n, '\0' );
for ( int i = 0; i < n; i++)
if (str[i] == ' ' )
result[i] = ' ' ;
int j = n - 1;
for ( int i = 0; i < str.length(); i++) {
if (str[i] != ' ' ) {
while (result[j] == ' ' )
j--;
result[j] = str[i];
j--;
}
}
return result;
}
int main()
{
string str = "internship at geeks for geeks" ;
cout << reverses(str) << endl;
return 0;
}
|
Java
public class ReverseStringPreserveSpace {
static void reverses(String str)
{
char [] inputArray = str.toCharArray();
char [] result = new char [inputArray.length];
for ( int i = 0 ; i < inputArray.length; i++) {
if (inputArray[i] == ' ' ) {
result[i] = ' ' ;
}
}
int j = result.length - 1 ;
for ( int i = 0 ; i < inputArray.length; i++) {
if (inputArray[i] != ' ' ) {
if (result[j] == ' ' ) {
j--;
}
result[j] = inputArray[i];
j--;
}
}
System.out.println(String.valueOf(result));
}
public static void main(String[] args)
{
reverses( "internship at geeks for geeks" );
}
}
|
Python3
def reverses(st):
n = len (st)
result = [ 0 ] * n
for i in range (n):
if (st[i] = = ' ' ):
result[i] = ' '
j = n - 1
for i in range ( len (st)):
if (st[i] ! = ' ' ):
if (result[j] = = ' ' ):
j - = 1
result[j] = st[i]
j - = 1
return ''.join(result)
if __name__ = = "__main__" :
st = "internship at geeks for geeks"
print (reverses(st))
|
C#
using System;
class GFG {
static void reverses( string str)
{
char [] inputArray = str.ToCharArray();
char [] result = new char [inputArray.Length];
for ( int i = 0; i < inputArray.Length; i++) {
if (inputArray[i] == ' ' ) {
result[i] = ' ' ;
}
}
int j = result.Length - 1;
for ( int i = 0; i < inputArray.Length; i++) {
if (inputArray[i] != ' ' ) {
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()
{
reverses( "internship at geeks for geeks" );
}
}
|
Javascript
<script>
function reverses(str)
{
let inputArray = str.split( "" );
let result = new Array(inputArray.length);
for (let i = 0; i < inputArray.length; i++) {
if (inputArray[i] == ' ' ) {
result[i] = ' ' ;
}
}
let j = result.length - 1;
for (let i = 0; i < inputArray.length; i++) {
if (inputArray[i] != ' ' ) {
if (result[j] == ' ' ) {
j--;
}
result[j] = inputArray[i];
j--;
}
}
document.write((result).join( "" ));
}
reverses( "internship at geeks for geeks" );
</script>
|
Output:
skeegrofsk ee gtapi hsn retni
Time complexity: O(N)
Auxiliary Space: O(N)
Optimized Solution:
The idea is to use two pointers to reverse.
C++
#include <iostream>
using namespace std;
void preserveSpace(string &str)
{
int n = str.length();
int start = 0;
int end = n - 1;
while (start < end) {
if (str[start] == ' ' ) {
start++;
continue ;
}
else if (str[end] == ' ' ) {
end--;
continue ;
}
else {
swap(str[start], str[end]);
start++;
end--;
}
}
}
int main()
{
string str = "internship at geeks for geeks" ;
preserveSpace(str);
cout << str;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
public static void preserveSpace(String str)
{
int n = str.length();
int start = 0 ;
int end = n - 1 ;
char [] Str = str.toCharArray();
while (start < end)
{
if (Str[start] == ' ' )
{
start++;
continue ;
}
else if (Str[end] == ' ' )
{
end--;
continue ;
}
else
{
char temp = Str[start];
Str[start] = Str[end];
Str[end] = temp;
start++;
end--;
}
}
System.out.println(String.valueOf(Str));
}
public static void main(String[] args)
{
String str = "internship at geeks for geeks" ;
preserveSpace(str);
}
}
|
Python3
def preserveSpace( Str ):
n = len ( Str )
Str = list ( Str )
start = 0
end = n - 1
while (start < end):
if ( Str [start] = = ' ' ):
start + = 1
continue
elif ( Str [end] = = ' ' ):
end - = 1
continue
else :
Str [start], Str [end] = ( Str [end],
Str [start])
start + = 1
end - = 1
print (''.join( Str ))
Str = "internship at geeks for geeks"
preserveSpace( Str );
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void preserveSpace( string str)
{
int n = str.Length;
int start = 0;
int end = n - 1;
char [] Str = str.ToCharArray();
while (start < end)
{
if (Str[start] == ' ' )
{
start++;
continue ;
}
else if (Str[end] == ' ' )
{
end--;
continue ;
}
else
{
char temp = Str[start];
Str[start] = Str[end];
Str[end] = temp;
start++;
end--;
}
}
Console.Write( new string (Str));
}
static void Main()
{
string str = "internship at geeks for geeks" ;
preserveSpace(str);
}
}
|
Javascript
<script>
function preserveSpace(str)
{
let n = str.length;
let start = 0;
let end = n - 1;
let Str = str.split( '' );
while (start < end)
{
if (Str[start] == ' ' )
{
start++;
continue ;
}
else if (Str[end] == ' ' )
{
end--;
continue ;
}
else
{
let temp = Str[start];
Str[start] = Str[end];
Str[end] = temp;
start++;
end--;
}
}
document.write(Str.join( "" ));
}
let str = "internship at geeks for geeks" ;
preserveSpace(str);
</script>
|
Output:
skeegrofsk ee gtapi hsn retni
Time complexity: O(n)
Auxiliary Space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!