Reversing vowels in a string JavaScript

We are required to write a JavaScript function that takes a string as input and reverse only the vowels of a string.

Problem Example

If the input string is:

const str = 'Hello';

Then the output should be:

'Holle'

Notice how 'e' and 'o' swap positions while consonants 'H', 'l', 'l' remain in their original places.

Solution Using Two Pointers

The most efficient approach uses two pointers from opposite ends of the string:

const str = 'Hello';

const reverseVowels = (str = '') => {
    const vowels = new Set(['a','e','i','o','u','A','E','I','O','U']);
    let left = 0, right = str.length - 1;
    let foundLeft = false, foundRight = false;
    str = str.split("");
    
    while(left 

Holle

How It Works

The algorithm uses a two-pointer technique:

  1. Convert string to array for easy character swapping
  2. Use a Set to store all vowels (both lowercase and uppercase) for O(1) lookup
  3. Move left pointer forward until it finds a vowel
  4. Move right pointer backward until it finds a vowel
  5. Swap the vowels when both pointers find them
  6. Continue until pointers meet

Testing with More Examples

const reverseVowels = (str = '') => {
    const vowels = new Set(['a','e','i','o','u','A','E','I','O','U']);
    let left = 0, right = str.length - 1;
    let foundLeft = false, foundRight = false;
    str = str.split("");
    
    while(left 

JAvAScritp
uoiea
bcdfg
UoIeA

Conclusion

This two-pointer approach efficiently reverses vowels in O(n) time complexity. The algorithm preserves consonant positions while only swapping vowels from opposite ends of the string.

Updated on: 2026-03-15T23:19:00+05:30

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements