Reverse only the vowels in a string while leaving all other characters in their original positions.
Problem
Given a string s, reverse the order of the vowels in s and return the resulting string.
The vowels are a, e, i, o, and u, and they may appear in either lowercase or uppercase form. Only vowels should change places; every non-vowel character must remain where it is.
What to do
Produce a new string in which:
- the vowel characters appear in reverse order compared with the input,
- all consonants, digits, punctuation, and other characters stay in the same index positions.
Notes
- Treat uppercase and lowercase vowels as vowels.
- The relative order of non-vowel characters is unchanged.
- You may think of this as swapping matching vowels from the two ends of the string until all vowel positions are handled.
Input Format
- A single string
s. smay contain lowercase letters, uppercase letters, digits, spaces, and punctuation.
Output Format
- Return a string with the vowels reversed and all other characters unchanged.
Constraints
0 <= |s| <= $10^{5}$- Characters are standard ASCII for typical interview use.
- The answer should run in linear time in the length of the string.
Example 1
Input
s = "hello"
Output
"holle"
Explanation
The vowels are e and o. Reversing them gives o and e, so the result is holle.
Example 2
Input
s = "leetcode"
Output
"leotcede"
Explanation
The vowels in order are e, e, o, e. Reversing them gives e, o, e, e at the same vowel positions.
Show 1 more example
Example 3
Input
s = "aA"
Output
"Aa"
Explanation
Uppercase and lowercase vowels are both considered vowels, so the two characters swap.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.