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.
1#include <stdbool.h>
2#include <string.h>
3#include <ctype.h>
4
5bool isVowel(char c) {
6 c = tolower(c);
7 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
8}
9
10char* reverseVowels(char* s) {
11 int left = 0, right = strlen(s) - 1;
12 while (left < right) {
13 while (left < right && !isVowel(s[left])) left++;
14 while (left < right && !isVowel(s[right])) right--;
15 if (left < right) {
16 char temp = s[left];
17 s[left] = s[right];
18 s[right] = temp;
19 left++;
20 right--;
21 }
22 }
23 return s;
24}
In this C solution, a helper function isVowel
is used to determine if a character is a vowel. We use two indices to traverse the string from both ends to find vowels. When both pointers land on vowels, the vowels are swapped, and the pointers are moved inward.
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
This JavaScript solution creates an Array to hold vowels and then replaces vowels in the string from this array. The pop operation ensures that vowels are placed correctly in reversed order.