[Solved] Reverse String Without Affecting Special Characters

Shape Image One
[Solved] Reverse String Without Affecting Special Characters

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


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

This question was asked in the Oracle interview.


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

Python Program

#convert string into list
while i<j:
    if not listSample[i].isalpha():
    elif not listSample[j].isalpha():
        #swap the element in the list 
        #if both elements are alphabets
        listSample[i], listSample[j]=listSample[j], listSample[i]

#convert list into string 
#by concatinating each element in the list



An isAlpha() is the character method that returns true if the character is an alphabet. Otherwise (if it is a special character), it returns false.

In Python, we can reverse the string with a single line of code. But, this is a special case where we don’t want to change the position of the special characters.

Similarly, you can solve this problem in C/C++ or Java.


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

Other Python Coding Questions for Practice:

This is the simple solution to reverse string without affecting special characters. Practice solving more of such coding questions to improve your programming skills.


  1. Hi,

    How to do code for below one?

    def reverse_each_word(sentence):
      # TODO: Implement this function
    def main():
      test_str =  "String; 2be reversed..."
      assert reverse_each_word(test_str) ==  "gnirtS; eb2 deserved..."
      return 0

    Sample Input:

    Input string = "String; 2be reversed..."
    Output: "gnirtS; eb2 deserved..."
    1. In this case, the words of the given string are reversed. Here is how you do this.

      1. Split the words from the strings
      2. Loop over all the words in the string
      3. Reverse each word and concatenate it to the output string.

      Let me know if it is not clear.

  2. yes not cleared

    def reverse_eachword(sentence):
     return " ".join([x[::-1] for x in sentence.split()]) 
    print(reverse_eachword("String; 2be reversed..."))

    but o/p is not coming as expected

  3. Hi Abhishek,

    below is code which work for you:

    str_smpl = 'String; 2be reversed...'
    lst = []
    for word in str_smpl.split(' '):
        letters = [c for c in word if c.isalpha()]
        for c in word:
            if c.isalpha():
        lst.append(' ')


    gnirtS; 2eb deserved...
  4. str = list('abcdefghijklmnopqrstuvwxyz')
    user_input = input("enter the value -- ")
    list0 = list(user_input)
    list1 = list(user_input)[::-1]
    def reverse(user_input):
        for i in list1:
            if i not in str:
        1. In your example, you have created an extra list (list1) of leght n. So the space complexity has increased to O(n).
          As you looping over the list only once, the time complexity is O(n) which is very efficient.

  5. How to get this output “gnirtS; eb2 desrever…” where the condition is:
    1. Reverse each word in the input string.
    2. The order of the words will be unchanged.
    3. A word is made up of letters and/or numbers.
    4. Other characters (spaces, punctuation) will not be reversed.

  6. how to collect words in advance and add them to the list already folded?
    The main check must pass.

    def reverse_string(str_smpl):
        lst = []
        for word in str_smpl.split(' '):
            letters = [c for c in word if c.isalpha()]
            for c in word:
                if c.isalpha():
            lst.append(' ')
    if __name__ == '__main__':
        cases = [
        ('aa1b d3c 13sgf%', 'ba1a c3d 13fgs%'),
        ('a1bcd efg!h', 'd1cba hgf!e'),
        ('abcd efgh', 'dcba hgfe'),
        ('', '')
        for text, reversed_text in cases:
            assert reverse_string(text) == reversed_text
      1. Can I reverse the string without changing the positions of special characters and without using string function like isalpha(), isalnum?

  7. Bro how do we revere the string without changing the position.
    Ex :

    #input = 'my name is rahul'
    #output = 'ym eman si lu'
      1. let input=”my name is rahul”
        let output=input.split(” “)

        let final=””
        for (i=0;i=0; j–){
        reverse += output[i][j]
        final+= reverse


Leave a Reply

Your email address will not be published. Required fields are marked *