345. Reverse Vowels of a String

#string #array #two-pointers

In a string s, reverse all the vowels in the string and return it.

Input: s = "IceCreAm"
Output: "AceCreIm"
Explanation: The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".

Intuition

  • we can swap the vowels in the front and back

Approach

  • use two pointer to track the vowel at the front and back

  • if both point to a vowel swap them

  • continue till the front and back pointer meet

Complexity

Space Complexity
Time Complexity

O(n)\text{O}(n)

O(n)\text{O}(n)

  • extra storage is used to store the string converted to char array

  • we iterate over the array only once

Code

class Solution {
    /**
     * check if character is a vowel irrespective of case
     */
    boolean isVowel(char x) {
        return (x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U' || x == 'a' || x == 'e' || x == 'i' || x == 'o'
                || x == 'u');
    }

    public String reverseVowels(String s) {
        char[] c = s.toCharArray();
        int size = s.length();

        if (size == 1)
            return s;

        for (int i = 0, j = size - 1; i < j;) {
            // move left pointer if its not pointing to vowel
            if (!isVowel(c[i]))
                i++;

            // move right pointer if its not pointing to vowel
            if (!isVowel(c[j]))
                j--;

            // swap if both pointing to vowel
            if (isVowel(c[i]) && isVowel(c[j])) {
                // swap
                char x = c[j];
                c[j] = c[i];
                c[i] = x;

                // move left & right pointer to next element
                i++;
                j--;
            }
        }

        return new String(c);
    }
}

Last updated