VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-string-preserving-space-positions/

⇱ Reverse a string preserving spaces - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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"

[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.

šŸ‘ Image


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.


Output
skeegrofsk ee gtapi hsn retni
Comment
Article Tags: