How to swap the vowles between in the strings

I have string

hello the vowels has to swap and the output is holle e and o is swapped

Below is my code

vowels = ['a','e','i','o','u']

first_str = 'aiao'
l = list(first_str)
vowel_list = []
for vowel in l :
    if vowel in vowels:
for index,value in enumerate(l):
    if value in vowels:
#         print(value)
        l[index] = vowel_list[-1]

I got output oaai Expected is also oaia

My Approach

  1. extract all vowels in list
  2. iterate over the string
  3. Swap the vowels while iterating from right side by putting [-1]
  4. After swap remove the element from the vowels list

edit courtesy @pranav using pop code is working ine

for index,value in enumerate(l):
    if value in vowels:
        l[index] = vowel_list.pop(-1)

>Solution :

Here you go

vowels = "aeiou"
str = 'aiao'
str = list(str)

i = 0 ; j = len(str)-1

while i < j:
    while i<j and str[i] not in v:
        i += 1
    while i<j and str[j] not in v:
        j -= 1
    str[i], str[j] = str[j], str[i]
    i += 1
    j -= 1


Approach : (Two Pointer Approach)

  1. Set two pointers(start and end of the string)
  2. Move the pointer until you find vowel
  3. Swap the characters at the pointers
  4. Repeat this until the pointers cross each other

Hope this solution helps

Leave a Reply