• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[Solved] Reverse String Without Affecting Special Characters

Aniruddha Chaudhari/53307/24
CodePython

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'

This question was asked in the Oracle interview.

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

Python Program

strSample='abc/defgh$ij'
 
#convert string into list
listSample=list(strSample)
 
i=0
j=len(listSample)-1
 
while i<j:
    if not listSample[i].isalpha():
        i+=1
    elif not listSample[j].isalpha():
        j-=1
    else:
        #swap the element in the list 
        #if both elements are alphabets
        listSample[i], listSample[j]=listSample[j], listSample[i]
        i+=1
        j-=1

#convert list into string 
#by concatinating each element in the list
strOut=''.join(listSample)
print(strOut)

Output:

jih/gfedc$ba

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.

Complexity

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:

  • Reverse Each Word in the Sentence using Python
  • Python Tricky Interview Coding Questions

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

Python Interview Questions eBook

coding challengePython
Aniruddha Chaudhari
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.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    abhishek
    April 1, 2020 at 12:30 pm

    Hi,

    How to do code for below one?

    def reverse_each_word(sentence):
      # TODO: Implement this function
      return
    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..."
    
    • Reply
      Aniruddha Chaudhari
      April 2, 2020 at 8:08 am

      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.

    • Reply
      Milan
      February 10, 2021 at 2:00 pm

      Hi Abishek, do you got the solution for that?

  • Reply
    rahul
    April 12, 2020 at 4:26 pm

    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

    • Reply
      Aniruddha Chaudhari
      April 13, 2020 at 8:17 am

      Rahul, the Program you have written is to reverse each individual word in the sentence.

      It returns.

      ;gnirtS eb2 ...desrever
  • Reply
    Aashish
    May 18, 2020 at 2:11 am

    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(letters.pop())
                continue
            else:
                lst.append(c)
        lst.append(' ')
    print("".join(lst))
    

    Output:

    gnirtS; 2eb deserved...
    • Reply
      Birobrata Deb
      January 25, 2021 at 10:58 am

      An additional space gets appended at the end of the reversed string: “gnirtS; 2eb desrever… “

  • Reply
    Santosh
    June 7, 2020 at 9:40 pm

    Hi,
    How do I include assert in the main() condition which must succeed upon error?

    • Reply
      Aniruddha Chaudhari
      June 8, 2020 at 4:10 pm

      I did not get your comment. You can refer to Python assert statement.

  • Reply
    Dwarakanath
    September 21, 2020 at 9:44 pm
    str = list('abcdefghijklmnopqrstuvwxyz')
    user_input = input("enter the value -- ")
    print(user_input)
    list0 = list(user_input)
    list1 = list(user_input)[::-1]
    def reverse(user_input):
        for i in list1:
            if i not in str:
                list1.remove(i)
                list1.insert(list0.index(i),i)
        print("".join(list1))
    reverse(user_input)
    
    • Reply
      Aniruddha Chaudhari
      September 22, 2020 at 4:42 pm

      Interesting. But, it will consume extra memory for strings and lists.

      • Reply
        Dwarakanath
        September 23, 2020 at 1:41 pm

        Thank you for your response. Can you please guide in memory management and time complexity?

        • Reply
          Aniruddha Chaudhari
          September 26, 2020 at 9:34 am

          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.

  • Reply
    Birobrata Deb
    January 24, 2021 at 9:21 pm

    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.

  • Reply
    Viazovik Anton
    April 30, 2021 at 2:49 pm

    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(letters.pop())
                    continue
                else:
                    lst.append(c)
            lst.append(' ')
        print("".join(lst))
    
    
    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
    
  • Reply
    k.gokulappadurai
    August 5, 2021 at 8:27 am
    #simply
    str=input() 
    print(str[::-1])
    
    • Reply
      Aniruddha Chaudhari
      August 9, 2021 at 8:54 am

      The code you shared is to reverse the string. We want to reverse the string without changing the positions of special characters.

      • Reply
        Kamath
        April 1, 2022 at 8:46 pm

        Can I reverse the string without changing the positions of special characters and without using string function like isalpha(), isalnum?

        • Reply
          Aniruddha Chaudhari
          April 5, 2022 at 11:25 am

          Yes. It is possible doing it manually instead of using a built-in function.

  • Reply
    Rahul
    February 11, 2022 at 12:03 pm

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

    #input = 'my name is rahul'
    #output = 'ym eman si lu'
    
    • Reply
      Rahul
      February 11, 2022 at 12:04 pm
      #input = 'my name is rahul'
      #output = 'ym eman si luhar
      
      • Reply
        Aniruddha Chaudhari
        July 30, 2022 at 12:29 pm

        Brother, I have already explained it.

        Refer this tutorial here- https://www.csestack.org/python-program-reverse-each-word-string/

      • Reply
        November 18, 2022 at 12:09 pm

        let input=”my name is rahul”
        let output=input.split(” “)

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

        console.log(final)

  • Reply
    Rameshwar Pawar
    August 9, 2022 at 3:50 pm

    pls, answer this code in java language.

Leave a Reply Cancel reply

Why?

Why Competitive Programming Important?

Coding Challenges for Practice

  1. Count Common Factor
  2. Does it Divide
  3. Sum of Sub Arrays
  4. Pair of Desired Sum
  5. Remove Duplicate Char from String
  6. Sort String by Char Freq (Python)
  7. Sort String by Char Freq (Java)
  8. Split Array into Equal Sum Subarray
  9. Validate IP Address
  10. Validate PAN Card Number
  11. Validate Sudoku
  12. Sort Circular Rotated Array
  13. String Permutations
  14. Min Arrow to Burst Bubbles
  15. Min Cost to Paint All Houses [Amazon]
  16. HourGlass with Max Sum
  17. Max Profit by Buying/Selling Stocks
  18. Hailstone Sequence
  19. Reverse String without affecting Special Characters
  20. Secure Conversation by Encry/Decry
  21. Special Elements in Matrix
  22. Next Greater No with Same set of Digits
  23. Smallest Subarray with Sum Greater than Given Number
  24. Group Anagrams
  25. Find Duplicates in Array in O(n)
  26. Find Two Unique Numbers from Array in O(n)
  27. Number Patterns & Finding Smallest Number
  28. First Unique Element in a Stream
  29. Flip Equivalent Binary Trees [TeachMint]
  30. Minimum Cost of Merging Files [Amazon]
  31. Minimum Distance for Truck to Deliver Order [Amazon]
  32. Longest Sequence of URLs
  33. Order Task for Given Dependencies
  34. Design Music Player
  35. Multilevel Parking System Design
  36. Minimum Coins Required
  37. Max Sum Subarray
  38. Max Avg Sum of Two Subsequences
  39. Merge Overlapping Intervals
  40. Longest Balanced Substring
  41. Longest Path in a Weighted Tree
  42. Generate Balanced Parentheses
  43. PostOrder Traversal Without Recursion

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard