[Solved] Reverse String Without Affecting Special Characters

Problem Statement: You have given a string. There can have multiple special characters inside the string. Write a program to reverse the given string. The position of the special characters should not be changed.

Example:

Input: 'abc/defgh$ij'
Output: 'jih/gfedc$ba'

Algorithm:
Here is a simple algorithm to solve this problem to reverse string without affecting special characters

Convert given string into a list (or array) such that every character in the string will be one element in the list.

Set the two pointers at the beginning of the list (says i) and at the end of the list (says j)

repeat while i<j:

if list[i] is a special character, increment i by 1

else if list[j] is a special character, decrement j by 1

else (list[i] and list[j] are alphabets) swap list[i] and list[j], increment i by 1 , decrement j by 1

We are traversing each character in the string at once. In the worst case, the time complexity is O(n), where n is the size of the given string.

We can do the in-place swapping of the characters of the string. So, it does not require any extra space. (In the case of Python, it’s not possible to swap the characters inside the string. So, we are obligated to use the list. This causes extra memory space.)

I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.