Given a string, reverse only the vowels in the string while keeping all other characters in their original positions. Vowels are a, e, i, o, u (both lowercase and uppercase). Return the resulting string.
For example, reversing vowels in "hello" produces "holle" (e and o swap). "leetcode" becomes "leotcede". "aA" becomes "Aa" (both vowels swap). "xyz" stays "xyz" (no vowels).
This problem teaches the two-pointer technique with a skipping condition. Only certain characters (vowels) are swapped, while non-vowels are left in place. This is a common variation of the standard two-pointer swap.
The solution uses two pointers, one at each end. While the left pointer is less than the right pointer, advance the left pointer until it points to a vowel, then advance the right pointer backward until it points to a vowel, then swap them and move both inward.
Edge cases include an empty string (return ""), a string with no vowels (return unchanged), a single character (return unchanged), and all vowels (full reversal of the vowel portion).
Example Input & Output
Case preserved
Vowels reversed
Empty string
Swap e and o
No vowels, unchanged
Algorithm Flow
Solution Approach
Use two pointers from both ends, skipping non-vowels and swapping when both pointers land on vowels.
Convert the string to a character array for swapping. Initialize two pointers. Use inner loops to skip non-vowels from both ends. When both pointers land on vowels, swap them and move inward. Continue until the pointers cross.
Time complexity is O(n), space complexity is O(n) for the character array.
Best Answers
class Solution {
public String solution(String s) {
char[] arr=s.toCharArray();String v="aeiouAEIOU";
int l=0,r=arr.length-1;
while(l<r){
while(l<r&&v.indexOf(arr[l])==-1)l++;
while(l<r&&v.indexOf(arr[r])==-1)r--;
if(l<r){char t=arr[l];arr[l]=arr[r];arr[r]=t;l++;r--;}
}return new String(arr);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
