618. Reversing Only the Vowels
A word of letters is given. Reverse the order of its VOWELS while leaving every other letter
exactly where it is. The vowels are a e i o u and their capitals.
Print the resulting word.
hello -> holle
leetcode -> leotcede
bcd -> bcd there is nothing to reverse
## The obvious method, and the sweep
Collecting the vowels, reversing that list, and writing them back into the vowel positions is correct and uses extra memory proportional to the number of vowels.
The sweep does it in place. Converge from both ends, skipping consonants, and swap whenever both pointers are sitting on a vowel:
i = 0, j = len-1
while i < j:
while i < j and s[i] is not a vowel: i += 1
while i < j and s[j] is not a vowel: j -= 1
if i < j:
swap s[i], s[j]
i += 1; j -= 1
This is the same skeleton as problem 612, with "compare" replaced by "swap". Recognising that two problems share a skeleton is worth more than remembering either one.
## The guard after the skips
The if i < j before the swap is not decoration. After the two skip loops the pointers may
have met, at a single vowel in the middle or at a position with no vowel at all. Swapping then
would either do nothing useful or, worse, run past the end in a version without the guard in
the inner loops.
a and bcd are the tests: one has a single vowel and the other none.
## Case is preserved by position, not by letter
The vowels move as they are, keeping their own case. aA becomes Aa, not aA.
This is worth stating because "reverse the vowels" is sometimes implemented as "sort out which
positions are vowels, then write the reversed sequence of vowel LETTERS lowercased", which
quietly changes the word. The test AEIOUbcd gives UOIEAbcd, and it catches that.
## Boundaries
A word with no vowels comes back unchanged. A word of one character comes back unchanged. A word that is all vowels is fully reversed.
## Cost
Time O(n). Space O(1) beyond the output.
Constraints - `1 ≤ length ≤ 200000` - the word contains only the letters `a-z` and `A-Z`
Input
One line containing a word of English letters, upper or lower case.
Output
Print the word with only its vowels reversed.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.