LeetCode – Reverse Vowels of a String (Java)

Write a function that takes a string as input and reverse only the vowels of a string.

Java Solution

this is a simple problem which can be solved by using two pointers scanning from beginning and end of the array.

public String reverseVowels(String s) {
    ArrayList<Character> vowList = new ArrayList<Character>();
    vowList.add('a');
    vowList.add('e');
    vowList.add('i');
    vowList.add('o');
    vowList.add('u');
    vowList.add('A');
    vowList.add('E');
    vowList.add('I');
    vowList.add('O');
    vowList.add('U');
 
    char[] arr = s.toCharArray();
 
    int i=0; 
    int j=s.length()-1;
 
    while(i<j){
        if(!vowList.contains(arr[i])){
            i++;
            continue;
        }
 
        if(!vowList.contains(arr[j])){
            j--;
            continue;
        }
 
        char t = arr[i];
        arr[i]=arr[j];
        arr[j]=t;
 
        i++;
        j--; 
    }
 
    return new String(arr);
}

3 thoughts on “LeetCode – Reverse Vowels of a String (Java)”

  1. Isn’t using List for checking membership of an element costly compared to HashSet or Maps? The former is O(n) and the later is O(1). As the vowel set is a non repeating thing, so I prefer using a set compared to Lists. Please provide your comments on the same.

  2. You are using extra space by having the string of vowels. Generally, unless you make things asymptotically better you shouldn’t worry much about constants. Lastly for both solutions you need to use a find operation essentially which is fastest done with a set (here since vowels are always a list of 10 things it doesn’t affect asymptotics, but it would become relevant if the question was reverse things from this set only).

  3. //Without using extra space (e.g. no list)


    public static String reverseVowels(String string) {
    String vowels = "aeiouAEIOU";

    int lo = 0;
    int hi = string.length() - 1;
    char[] ch = string.toCharArray();

    while (lo < hi) {
    if (!vowels.contains(String.valueOf(string.charAt(lo)))) {
    lo++;
    continue;
    }

    if (!vowels.contains(String.valueOf(string.charAt(hi)))) {
    hi--;
    continue;
    }

    // swap
    swap(ch, lo, hi);
    lo++;
    hi--;
    }
    return String.valueOf(ch);
    }

    private static void swap(char[] ch, int lo, int hi) {
    char tmp = ch[lo];
    ch[lo] = ch[hi];
    ch[hi] = tmp;
    }

Leave a Comment