Code Logo

Reverse Vowels Only

Published at25 Jul 2026
Medium 1 views
Like0

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

Example 1
Input
"aA"
Output
"Aa"
Explanation

Case preserved

Example 2
Input
"leetcode"
Output
"leotcede"
Explanation

Vowels reversed

Example 3
Input
""
Output
""
Explanation

Empty string

Example 4
Input
"hello"
Output
"holle"
Explanation

Swap e and o

Example 5
Input
"xyz"
Output
"xyz"
Explanation

No vowels, unchanged

Algorithm Flow

Recommendation Algorithm Flow for Reverse Vowels Only

Solution Approach

Use two pointers from both ends, skipping non-vowels and swapping when both pointers land on vowels.

function reverseVowels(s)
  chars = array of characters from s
  i = 0, j = length(chars) - 1
  vowels = set of "aeiouAEIOU"
  while i < j
    while i < j and chars[i] not in vowels: i = i + 1
    while i < j and chars[j] not in vowels: j = j - 1
    swap chars[i] and chars[j]
    i = i + 1, j = j - 1
  return string from chars

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

java
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);
    }
}