How to swap the vowles between in the strings

Question:

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:
        vowel_list.append(vowel)
for index,value in enumerate(l):
    if value in vowels:
#         print(value)
        l[index] = vowel_list[-1]
        vowel_list.remove(vowel_list[-1]) 
        print(vowel_list)
''.join(l)

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)
''.join(l)
Asked By: abd

||

Answers:

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 vowels:
        i += 1
    while i<j and str[j] not in vowels:
        j -= 1
    str[i], str[j] = str[j], str[i]
    i += 1
    j -= 1

print("".join(str))
    

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

Answered By: Lokesh Senthil
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.