🔗 Problem Link
LeetCode 345 – Reverse Vowels of a String
👉 https://leetcode.com/problems/reverse-vowels-of-a-string/
Introduction
This problem is very similar to Reverse Only Letters, but with a small twist:
Instead of reversing all letters, we only reverse the vowels.
At first, we might think of extracting vowels, reversing them, and putting them back. That works — but it is not the most optimal approach.
In this article, we’ll:
- Understand the brute-force style approach (your solution)
- Analyze its time complexity
- Optimize it using the Two Pointer pattern
- Compare both approaches
📌 Problem Understanding
You are given a string s.
You must:
- Reverse only the vowels
- Keep all other characters in the same position
Vowels include:
Example 1
Vowels: ['I','e','e','A']
Reversed: ['A','e','e','I']
Example 2
🧠 Your First Approach – Extract, Reverse, Replace
Your idea:
- Extract all vowels into a string.
- Store their indices.
- Reverse the vowel string.
- Replace vowels at stored indices.
Let’s look at your code.
💻 Your Code (Extract & Replace Method)
🔍 How This Works
Step 1 – Extract Vowels
Store:
- Vowel characters in
vow - Their indices in
lis
Step 2 – Reverse the Vowel String
Create new reversed string so.
Step 3 – Map Indices to Reversed Vowels
Use a HashMap to store:
Step 4 – Build Final String
Traverse original string:
- If index in map → use reversed vowel
- Else → use original character
⚠️ Problem with This Approach
Although correct, it has inefficiencies:
- String concatenation (
+=) → O(n²) in worst case - Extra space used:
- Vowel string
- List of indices
- HashMap
- Final answer string
Time Complexity: O(n²) (due to string concatenation)
Space Complexity: O(n)
We can do better.
🚀 Optimized Approach – Two Pointers (Best Solution)
Instead of extracting vowels separately, we can:
- Convert string into char array
- Use two pointers
- Swap vowels directly
This avoids extra structures.
💻 Optimized Two Pointer Solution
🎯 Why This Works
We:
- Move left pointer until vowel found
- Move right pointer until vowel found
- Swap
- Continue
No extra storage needed.
⏱ Complexity Comparison
Your Approach
- Time: O(n²) (string concatenation)
- Space: O(n)
Two Pointer Approach
- Time: O(n)
- Space: O(n) (char array)
Much cleaner and faster.
🔥 Key Learning
This problem reinforces:
- Two pointer pattern
- In-place modification
- Avoiding unnecessary extra space
- Recognizing optimization opportunities
Whenever you see:
"Reverse something but keep other elements fixed"
Think:
👉 Two Pointers
🏁 Final Thoughts
Your approach shows strong logical thinking:
- Extract → Reverse → Replace
That’s a valid way to solve it.
But the optimized two-pointer approach is more interview-friendly.
If you master this pattern, you can easily solve:
- Reverse Only Letters
- Reverse String
- Valid Palindrome
- Remove Duplicates from Sorted Array




