Similar Problems

Similar Problems not available

Reverse Vowels Of A String - Leetcode Solution

LeetCode:  Reverse Vowels Of A String Leetcode Solution

Difficulty: Easy

Topics: string two-pointers  

Problem Statement:

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello" Output: "holle"

Example 2:

Input: "leetcode" Output: "leotcede"


  • The vowels does not include the letter "y".


The problem can be solved by keeping two pointers, one at the start of the string and one at the end. We'll then swap the vowels at the two positions and move the pointers towards the middle until they meet.

We'll have to check if a character is a vowel or not. We can do this by creating a set of all the vowels and then checking if a character is in the set or not.

Once we swap the vowels at the two positions, we'll continue the process until the two pointers meet at the middle.


class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
        s = list(s)
        l, r = 0, len(s) - 1
        while l < r:
            if s[l] in vowels and s[r] in vowels:         # Check whether the element is vowel or not
                s[l], s[r] = s[r], s[l]                  # Swap the vowels
                l += 1
                r -= 1
            elif s[l] not in vowels:
                l += 1                                   # Move the left pointer if the character in s[l] is not a vowel
            elif s[r] not in vowels:
                r -= 1                                   # Move the right pointer if the character in s[r] is not a vowel
        return ''.join(s)                                # Return the updated string


We'll test our function with some inputs:

s = Solution()
assert s.reverseVowels("hello") == "holle"
assert s.reverseVowels("leetcode") == "leotcede"
assert s.reverseVowels("aeiou") == "uoiea"
assert s.reverseVowels("bcdfg") == "bcdfg"
assert s.reverseVowels("AaEeIiOoUu") == "UuOoIiEeAa"
print("All test cases passed")


All test cases passed

Reverse Vowels Of A String Solution Code