Problem Description
Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u' which can appear in both lower and upper cases.
Key Insights
- Use two pointers, one starting from the beginning and one from the end of the string.
- Identify vowels quickly using a set for constant time lookups.
- Only swap characters when both pointers reference vowels.
- Increment pointers accordingly when non-vowel characters are encountered.
- The approach runs in a single pass, leading to an efficient O(n) solution.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n) (if considering the conversion of the string into a list for in-place modification; otherwise, O(1) extra space if the string was mutable)
Solution
We solve the problem by first converting the input string into a mutable list structure so we can swap characters easily. The two pointers—one starting at the beginning (left) and one at the end (right)—are used to traverse towards the center. For each pointer, we check if the current character is a vowel by using a set containing both lowercase and uppercase vowels. When both pointers reference vowels, we swap them and move both pointers inward. If only one of the pointers points to a vowel, we adjust the other pointer accordingly. This way, we only reverse the vowels in the string while leaving other characters untouched.