Open In App

Python Program to Reverse consonants in a given string without affecting the other elements

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Examples:

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.

Reverse consonants in a given string

Consonant Replacement in a String

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

Implementation

Below is the implementation of the above approach.

Python3




# Function to check element is consonant or not
def isConsonant(i):
    vow = ['a', 'e', 'i', 'o', 'u']
     
    # if not vowel return true
    if i not in vow:
        return True
    return False
 
 
def reverseConsonant(s):
   
    # convert string into list
    s = list(s)
     
    # storing consonants in a list
    cons = []
    for i in s:
        if isConsonant(i):
            cons.append(i)
    k = len(cons)-1
     
    # Replace the consonants with the
    # element present in consonant list
    # from last.
    for i in range(len(s)):
        if isConsonant(s[i]):
            s[i] = cons[k]
            k -= 1
    return "".join(s)
 
print(reverseConsonant("hello world"))
print(reverseConsonant("bcdfghjklm"))


Output

delrow ollh
mlkjhgfdcb

Complexity Analysis

Time complexity: O(n)

Space Complexity: O(n) for storing consonants

List Comprehension with String Iteration

Approach:

  1. Generate a list of consonants from the input string using a list comprehension.
  2. Reverse the list of consonants.
  3. Initialize a string variable to store the modified string.
  4. Iterate through the input string, replacing consonants with the reversed consonants from the list generated in step 1.
  5. Append non-consonants as is to the modified string.
  6. Return the modified string.
     

Python3




def reverse_consonants(input_string):
    # Generate a list of consonants from the input string
    consonants = [char for char in input_string if char.isalpha() and char.lower() not in ['a', 'e', 'i', 'o', 'u']]
     
    # Reverse the list of consonants
    consonants.reverse()
     
    # Initialize a string variable to store the modified string
    output_string = ''
     
    # Iterate through the input string and replace consonants with reversed consonants
    for char in input_string:
        if char.isalpha() and char.lower() not in ['a', 'e', 'i', 'o', 'u']:
            output_string += consonants.pop(0)
        else:
            output_string += char
     
    # Return the modified string
    return output_string
 
input_string = "hello"
print(reverse_consonants(input_string))


Output

lelho

Time Complexity: O(n)
Auxiliary Space: O(n)

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:

  1. Define a function reverse_consonants that takes a string as input.
  2. Convert the string to a list of characters so we can modify it.
  3. Initialize two pointers, the left pointing to the beginning of the string and the right pointing to the end of the string.
  4. Define a set of consonants to check if a character is a consonant.
  5. While left is less than right, check if both characters at left and right pointers are consonants.
  6. If both are consonants, swap them and move both pointers toward the middle.
  7. 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.
  8. Convert the modified list back to a string and return it.

Python3




# Python program for the above approach
 
# Function to reverse the consonants of
# the given string
def reverse_consonants(s):
   
    # convert string to list of characters
    s_list = list(s)
     
    # initialize pointers
    left = 0
    right = len(s) - 1
     
    # define set of consonants
    consonants = set('bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ')
     
    # while pointers don't meet
    while left < right:
        if s_list[left] in consonants and s_list[right] in consonants:
           
            # swap consonants
            s_list[left], s_list[right] = s_list[right], s_list[left]
            left += 1
            right -= 1
        elif s_list[left] not in consonants:
            left += 1
        elif s_list[right] not in consonants:
            right -= 1
             
    # convert list back to string and return
    return ''.join(s_list)
 
# Driver Code
s = 'hello'
 
print(reverse_consonants(s))


Output

lelho

Time complexity: O(n) since we only iterate through the string once.

Auxiliary space: O(n)



Last Updated : 27 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads