Reverse Vowels of a String
String Simulation
Problem
Write a function that takes a string as input and reverse only the vowels of a string.
Thought Process
You can use 2 pointer approach for this problem
We have to convert the string to a list in order to reassign elements
Solution
class Solution:
def reverseVowels(self, s: str) -> str:
s = list(s)
# converting string to list
# because strings do not support
# item assignment
vowels = 'aeiouAEIOU'
i = 0
j = len(s)-1
while i < j:
while i < j and s[i] not in vowels: #finding the first vowel we come across
i+=1
while i < j and s[j] not in vowels: #finding the first vowel we come across
j-=1
s[i], s[j] = s[j], s[i]
i+=1
j-=1
return "".join(s)
Time Complexity
Time: O(n) since we are using the two pointer approach and going linearly. Also, when we look up to see if the element is a vowel, it will take O(10) which is just O(1)
Space: O(1)
Last updated
Was this helpful?