Reverse Vowels · Optimal Solution

Swap only the vowels, leave the frame intact.

A typographer mirrors only the vowel glyphs in a display string while leaving consonants fixed — reflecting 'hello' to 'holle'. Two pointers converge from opposite ends, each skipping consonants. Only when both land on a vowel do they swap. The consonant skeleton stays intact while the vowels reflect across it. O(n) time. O(n) space for the character array.


Interactive

Watch two pointers converge and swap


Concept

The two-pointer vowel invariant

The left pointer only advances past consonants; the right pointer only retreats past consonants. A swap happens exactly when both pointers sit on vowels — guaranteeing every vowel finds its mirror partner.

left pointer

Scans rightward from the start, skipping every consonant until it finds a vowel or meets the right pointer.

right pointer

Scans leftward from the end, skipping every consonant until it finds a vowel or meets the left pointer.

vowel swap

When both pointers rest on vowels, the characters swap. Both pointers then step inward and the search continues.


Algorithm

Convert, converge, swap, rebuild

  1. 1

    Convert the string to a char array

    Strings are immutable, so copy the characters into a mutable array to allow in-place swaps.

  2. 2

    Initialize two pointers

    Set left = 0 and right = length − 1. They will walk toward each other.

  3. 3

    Skip consonants, swap vowels

    While left < right: skip left if it's a consonant, skip right if it's a consonant, otherwise swap both characters and advance both pointers inward.

  4. 4

    Return the new string

    Join the modified char array back into a string. All vowels are now reversed; consonants remain in place.


Edge Cases

Where the pointers reveal the structure

No vowels at all

Both pointers race past consonants until they cross. No swap ever occurs — the string returns unchanged. The algorithm gracefully handles consonant-only inputs like "rhythm."

All vowels

Every character is a vowel, so neither pointer ever skips. The string fully reverses — identical to reversing the whole string. The algorithm performs ⌊n/2⌋ swaps.

Palindrome vowels

When the vowel sequence reads the same forwards and backwards, swaps still happen but produce the same characters. The output equals the input — e.g., "racecar" stays "racecar."