🧩 Problem Statement
Given a string s
, reverse only the vowels of the string and return the resulting string.
🔢 Example
python
Input: s = "hello"
Output: "holle"
Input: s = "leetcode"
Output: "leotcede"
✅ Constraints
1 <= s.length <= 3 * 10⁵
s
consists of printable ASCII characters.
💡 Key Concept: Two-Pointer Strategy
This problem is a classic case for the two-pointer approach where you:
- Start one pointer from the left (
i
)
- Start another from the right (
j
)
- Move inward until both pointers find vowels, then swap them
- Continue until the pointers meet
🧠 Step-by-Step Plan
- Define a set of vowels:
{'a', 'e', 'i', 'o', 'u'}
- Use two pointers:
i = 0
(start)
j = len(s) - 1
(end)
- Move
i
forward and j
backward until both point to vowels
- Swap the vowels
- Join and return the modified string
✅ Python Code – Two-Pointer Approach
python
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set("aeiouAEIOU")
s = list(s) # Convert string to list for in-place swaps
i, j = 0, len(s) - 1
while i < j:
if s[i] not in vowels:
i += 1
continue
if s[j] not in vowels:
j -= 1
continue
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return ''.join(s)
🔍 Example Walkthrough: "hello"
s = ["h", "e", "l", "l", "o"]
- Vowels:
e
(index 1), o
(index 4)
- Swap →
["h", "o", "l", "l", "e"]
- Result =
"holle"
⏱️ Time and Space Complexity
MetricValueTime ComplexityO(n)Space ComplexityO(n)
Note: Space is O(n) because strings are immutable in Python, so we convert it to a list for modification.
📦 Edge Test Cases
python
Input: "aA" → Output: "Aa"
Input: "bcdfg" → Output: "bcdfg" # No vowels
Input: "Euston" → Output: "oustEn"
Input: "AaEeIiOoUu" → Output: "uUoOiIeEaA"
✅ Conclusion
LeetCode 345: Reverse Vowels of a String is a great follow-up to the classic reverse string problem. It strengthens your grip on the two-pointer technique, string traversal, and character-level manipulation.
This problem often appears in interviews to test how well you can modify a subset of a structure in-place and efficiently.