Reverse Vowels of a String
The key idea
Only the vowels move; every consonant stays put. Walk two pointers from both ends inward, and whenever both land on a vowel, swap them. This reverses the vowels in place without touching anything else.
Problem
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Constraints
- 1 <= s.length <= 3 * 10^5
- s consist of printable ASCII characters
Examples
Input: s = "IceCreaM"
Output: "AceCreaI"
Input: s = "leetcode"
Output: "leotcede"
Complexity
Time: O(n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Two Pointers problems
- 3SumMEDIUM
- 4SumMEDIUM
- Concatenation of ArrayEASY
- Container With Most WaterMEDIUM
- Is SubsequenceEASY
- Merge Sorted ArrayEASY
- Merge Strings AlternatelyEASY
- Move ZeroesEASY
- Next PermutationMEDIUM
- Remove Duplicates from Sorted ArrayEASY
- Remove Duplicates from Sorted Array IIMEDIUM
- Remove ElementEASY