Intuition
Use two pointer technique
- Initialize set with vowels, res array that we will use to swap values and left pointer and right pointer
- while l less than r
- skip all non vowels and swap when l and r both land on vowels
Optimal Solution
class Solution:
def reverseVowels(self, s: str) -> str:
d = {'a','e','i','o','u','A','E','I','O','U'}
res = [c for c in s]
l,r = 0, len(s)-1
while l < r:
while s[l] not in d and l < r:
l += 1
while s[r] not in d and l < r:
r -= 1
if l < r:
res[l],res[r] = res[r],res[l]
l += 1
r -= 1
return "".join(res)
Time Complexity
Time Complexity O(N)
Space Complexity O(N)