Sponsored
Sponsored
The two pointers approach involves using two indices, one starting at the beginning and the other at the end of the string. You check and swap vowels as they are encountered using these pointers, moving them inward toward each other. This method is efficient as it requires a single pass through the string, with each character processed a maximum of two times.
Time Complexity: O(n), where n is the length of the string, as each character is processed at most twice.
Space Complexity: O(1) as no additional space is used aside from variables.
1function reverseVowels(s) {
2 let vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
3 let arr = s.split('');
4 let left = 0, right = arr.length - 1;
5 while (left < right) {
6 while (left < right && !vowels.has(arr[left])) left++;
7 while (left < right && !vowels.has(arr[right])) right--;
8 if (left < right) {
9 [arr[left], arr[right]] = [arr[right], arr[left]];
10 left++;
11 right--;
12 }
13 }
14 return arr.join('');
15}
This JavaScript solution uses a Set to determine vowel membership and an array to facilitate easy swapping of characters. Two pointers are used to traverse the string efficiently.
This approach uses a stack to collect all vowels in the string as they are encountered in a single pass. Then, it makes a second pass through the string to replace vowels, using the stack to supply the reversed vowels. This approach is straightforward but might not be as time efficient as the two pointers approach.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n) for storing vowels separately.
1
In this C solution, we maintain an auxiliary buffer (string) to store vowels as we encounter them. During the second iteration of the string, we replace vowels using the stored buffer in reverse order.