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
List Comprehension with String Iteration
- Generate a list of consonants from the input string using a list comprehension.
- Reverse the list of consonants.
- Initialize a string variable to store the modified string.
- Iterate through the input string, replacing consonants with the reversed consonants from the list generated in step 1.
- Append non-consonants as is to the modified string.
- Return the modified string.
Time Complexity: O(n)
Auxiliary Space: O(n)
Method: Two-Pointer Approach for Reversing Consonants in a String
The idea is to use two pointers, one starting from the beginning of the string and one from the end. We check if the characters at both pointers are consonants. If both characters are consonants, we swap them and move both pointers toward each other until they meet in the middle. If one or both characters are vowels, we simply move the corresponding pointer toward the middle. Below are the steps:
- Define a function reverse_consonants that takes a string as input.
- Convert the string to a list of characters so we can modify it.
- Initialize two pointers, the left pointing to the beginning of the string and the right pointing to the end of the string.
- Define a set of consonants to check if a character is a consonant.
- While left is less than right, check if both characters at left and right pointers are consonants.
- If both are consonants, swap them and move both pointers toward the middle.
- If the left character is not a consonant, move the left pointer toward the middle and if the right character is not a consonant, move the right pointer toward the middle.
- Convert the modified list back to a string and return it.
Time complexity: O(n) since we only iterate through the string once.
Auxiliary space: O(n)
Please Login to comment...