LeetCode 345. Reverse Vowels of a String

Dec 22, 2025

Intuition

Use two pointer technique

  1. Initialize set with vowels, res array that we will use to swap values and left pointer and right pointer
  2. while l less than r
  3. 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)

Steve Jin