Python Program to Reverse consonants in a given string without affecting the other elements
Given a string, the task is to write a Python program to reverse only the consonants of a string without affecting the other elements’ positions.
Input : hello
Output : lelho
Explanation: h,l,l are consonants in the given string. After modifying the string their occurrences are l,l,h and vowels positions are not changed.
- Convert the string into a list of characters.
- Maintain another Python list for storing consonants.
- If the current element is consonant then append the current element to the consonant list.
- Start traversing the list again and replace the consonants with the element present in the consonant list from last.
- Finally, convert the list into a string and return it.
Below is the implementation of the above approach.
delrow ollh mlkjhgfdcb
Time complexity: O(n)
Space Complexity: O(n) for storing consonants
My Personal Notes arrow_drop_up
Please Login to comment...