Introduction
The Reverse Vowels of a String problem is a popular string manipulation challenge that tests your ability to selectively modify characters within a string. Given a string s
, the task is to reverse only the vowels—both lowercase (a
, e
, i
, o
, u
) and uppercase (A
, E
, I
, O
, U
)—while keeping all non-vowel characters in their original positions.
Table of Contents
This problem strengthens your understanding of two-pointer techniques and character-based filtering. By learning how to identify vowels efficiently and swap them in place, you build a strong foundation for handling more complex string editing problems.
In this explanation, we’ll walk through an optimal and Pythonic approach to solve the Reverse Vowels of a String problem step-by-step along the way.
Example 1:
Input: s = "hello"
Output: "holle"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Constraints:
1 <= s.length <= 3 * 10^5
s
consists of printable ASCII characters
Python Solution
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set("aeiouAEIOU")
s = list(s)
i, j = 0, len(s) - 1
while i < j:
while i < j and s[i] not in vowels:
i += 1
while i < j and s[j] not in vowels:
j -= 1
# Swap vowels
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return ''.join(s)
Step-by-Step Explanation
Step 1: Define Vowels Set
vowels = set("aeiouAEIOU")
- We use a
set
for O(1) lookup time when checking if a character is a vowel. - It includes both lowercase and uppercase vowels.
Step 2: Convert String to List
s = list(s)
- Strings are immutable in Python, so we convert the string to a list to allow in-place swapping.
Step 3: Initialize Two Pointers
i, j = 0, len(s) - 1
- Use a two-pointer approach:
i
starts from the beginning,j
from the end.
Step 4: Find Next Vowel from Each End
while i < j and s[i] not in vowels:
i += 1
while i < j and s[j] not in vowels:
j -= 1
- Move the pointers inward until both
s[i]
ands[j]
are vowels. - These while-loops skip consonants and non-vowel characters.
Step 5: Swap the Vowels
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
- Swap the vowels found at positions
i
andj
. - Then move both pointers inward to continue searching for more vowels.
Step 6: Return the Modified String
return ''.join(s)
- Convert the list of characters back into a string and return it.
Time and Space Complexity
- Time Complexity:
O(n)
- Each character is visited at most once.
- Space Complexity:
O(n)
- Due to list conversion and string joining (could be
O(1)
if done in-place with a character array in other languages).
- Due to list conversion and string joining (could be
This solution uses the two-pointer technique to efficiently reverse vowels in a string while maintaining the positions of all other characters.