Code Logo

Reverse Vowels Only

Published at25 Jul 2026
Medium 0 views
Like0

Given a string s, reverse only the vowels in the string. Vowels are 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase). All other characters and their positions stay the same.

Use two pointers: one from the left and one from the right. Move both toward the center. When both pointers point to vowels, swap them. This is an in-place reversal of only the vowels using O(1) extra space beyond the string conversion.

Time complexity is O(n) with O(1) extra space. The two-pointer technique is efficient and avoids creating intermediate data structures.

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
Recommendation Algorithm Flow for Reverse Vowels Only

Solution Approach

function solution(s) {
  var arr = s.split('');
  var v = 'aeiouAEIOU';
  var 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) { var t = arr[l]; arr[l] = arr[r]; arr[r] = t; l++; r--; }
  }
  return arr.join('');
}

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