Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
- Convert string to array for easy character swapping
- Use a Set to store all vowels (both lowercase and uppercase) for O(1) lookup
- Move left pointer forward until it finds a vowel
- Move right pointer backward until it finds a vowel
- Swap the vowels when both pointers find them
- 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.
Advertisements
