![]() |
VOOZH | about |
Given a string s, reverse only the vowels in s while keeping the other characters in their original positions.
Examples:
Input: "geeksforgeeks"
Output: "geeksforgeeks"
Explanation: The vowels 'e', 'e', 'o', 'e', 'e' are reversed, resulting in "geeksforgeeks".Input: "helloworld"
Output: "hollowerld"
Explanation: The vowels 'e', 'o', 'o' are reversed, resulting in "hollowerld".Input: "programming"
Output: "prigrammong"
Explanation: The vowels 'o', 'a', 'i' are reversed, resulting in "prigrammong".
Table of Content
The idea is to extract all vowels from the given string s and store them in vowelStr while maintaining their order. Then, we iterate through s again, replacing each vowel with the last stored vowel from vowelStr, effectively reversing their positions. This approach works because only vowels are modified, while consonants remain in place.
Below is the implementation of the above approach:
geeksforgeeks
Time Complexity: O(n), as first pass collects vowels, second pass replaces them in reverse order, and each pass costs O(n).
Space Complexity:O(n), as extra space is used to store vowels separately.
The idea is to use the Two Pointers technique to efficiently reverse only the vowels in the string while keeping other characters in place. We maintain left and right pointers, moving them inward until they find a vowel. Once both pointers point to vowels, we swap them.
Steps to implement the above idea:
Below is the implementation of the above approach:
geeksforgeeks
Time Complexity: O(n), as each character is processed at most once.
Space Complexity: O(1), since only a few extra variables are used.