Reverse Vowels of a String

Reverse the order of the vowels in a string while every other letter stays where it is.

Given a string s, reverse only the vowels and return the result. The vowels are a, e, i, o and u, in lowercase or uppercase. All other characters keep their positions.

Example 1
Input: s = "hello"
Output: "holle"
Explanation: the vowels e and o swap places.
Example 2
Input: s = "deepnote"
Output: "deopnete"
Explanation: the vowels e, e, o, e become e, o, e, e.
Solution

The Idea

Think of the word as a row of letter tiles. The consonant tiles are glued down, and only the vowel tiles may be picked up and put back. In "hello" the loose tiles are e and o. Reversed, they read o and e, and putting them back into the same two slots gives "holle".

With two vowels, reversing is just one swap. Example 2 has more. In "deepnote" the vowels sit at positions 1, 2, 5 and 7, counting from 0, and read e, e, o, e. Reversed they read e, o, e, e, and written back into positions 1, 2, 5 and 7 they give "deopnete". So how do we move them without first copying all the vowels out?

Reversing any list follows a simple pattern: the first item swaps with the last, the second with the second to last, and so on toward the middle. Here the list is the vowels, so the first vowel swaps with the last vowel, then the second vowel with the second to last. Look at the picture below.

The word deepnote has vowels at positions 1, 2, 5 and 7. The first swap exchanges the e at 1 with the e at 7, the second swap exchanges the e at 2 with the o at 5, giving deopnete.

The row labelled "before" is "deepnote". The outer arc, labelled "first swap: e and e", exchanges the e at position 1 with the e at position 7, which changes nothing you can see. The inner arc, labelled "second swap: e and o", exchanges the e at position 2 with the o at position 5. The row labelled "after" reads "deopnete", the expected answer.

So we need two markers: one that walks in from the left and stops at each vowel, and one that walks in from the right and does the same. Every time both have stopped, their two vowels swap. Two markers like these, moving toward each other from the two ends, are called two pointers.

Solution Approach

Turning that idea into code means settling four things: where to make the changes, how to recognise a vowel, how each pointer finds its next vowel, and when to stop.

Where the letters change

Can we swap two letters inside a Java String? No: a String cannot be changed once it is made. So the method copies the letters into a char array with toCharArray(), swaps inside the array, and builds the answer from it at the end with new String(...).

A simpler way also works: copy all the vowels into a list in one pass, then walk the string a second time and write them back from the end of the list. It takes the same order of time, but needs that extra list and a second pass. The two pointers do the job in one pass with nothing extra.

Recognising a vowel

How do we test one character? The string "aeiouAEIOU" holds all ten vowels, both cases. Its indexOf(ch) returns the position of ch in it, or -1 when ch is not there. So a character is a vowel when that position is 0 or more. Listing the uppercase letters too is what lets a word with capital vowels, such as "IceCreAm", work.

Finding the next vowel

What does each pointer do between swaps? The left pointer, lo, starts at position 0 and steps right past every consonant until it lands on a vowel. The right pointer, hi, starts at the last position and steps left in the same way. After a swap, both step one place inward, past the vowels they just used, and the search starts again.

Stopping in the middle

When are we done? Once lo is no longer left of hi, every vowel on the left has been paired with one on the right. The searches for the next vowel must check this too. Without that check, the pointers can walk past each other and swap vowels that were already swapped, or run off the end of the array when there are no vowels at all.

Java Solution

The method reverseVowels works in these steps:

  1. First, copy the string into a char array c with s.toCharArray(), and set lo to 0 and hi to the last position.
  2. Repeat the next three steps in an outer loop for as long as lo is less than hi.
  3. Inside it, a first inner loop moves lo right while c[lo] is not a vowel. A second inner loop moves hi left while c[hi] is not a vowel. Both inner loops also stop as soon as lo reaches hi.
  4. Swap c[lo] and c[hi] through a temporary variable tmp.
  5. Move lo one place right and hi one place left.
  6. When the outer loop ends, return new String(c).

The helper isVowel does the vowel test with "aeiouAEIOU".indexOf(ch). The main method runs both examples, a word with uppercase vowels, a word with no vowels, a word with one vowel, and the empty string, printed between brackets so it shows up.

Java
public class ReverseVowelsOfString {

    public static String reverseVowels(String s) {
        char[] c = s.toCharArray();
        int lo = 0;
        int hi = c.length - 1;
        while (lo < hi) {
            while (lo < hi && !isVowel(c[lo])) {
                lo++;                         // find the next vowel from the left
            }
            while (lo < hi && !isVowel(c[hi])) {
                hi--;                         // and the next vowel from the right
            }
            char tmp = c[lo];
            c[lo] = c[hi];
            c[hi] = tmp;
            lo++;
            hi--;
        }
        return new String(c);
    }

    private static boolean isVowel(char ch) {
        return "aeiouAEIOU".indexOf(ch) >= 0;
    }

    public static void main(String[] args) {
        System.out.println(reverseVowels("hello"));
        System.out.println(reverseVowels("deepnote"));
        System.out.println(reverseVowels("IceCreAm"));
        System.out.println(reverseVowels("xyz"));
        System.out.println(reverseVowels("bab"));
        System.out.println("[" + reverseVowels("") + "]");
    }
}

Running it prints:

Output
holle
deopnete
AceCreIm
xyz
bab
[]

holle and deopnete match the two examples. In the third line, "IceCreAm" became AceCreIm: the uppercase I at the front and the uppercase A near the end traded places, and the two e's in the middle swapped with each other.

xyz comes back as it went in. lo finds no vowel and stops when it reaches hi, so the only swap exchanges the z with itself. In bab both pointers stop on the single a, which also swaps with itself. The empty string prints as []: hi starts at -1, so the outer loop never runs.

The lo < hi checks in the inner loops matter. With them removed, "hello" comes back as hello: after the first swap the pointers walk past each other and swap e and o back. "xyz" throws ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3, because lo runs off the end looking for a vowel.

Complexity

The work is one walk of the two pointers toward each other, plus the copy into the array.

  • Time: O(n), where n is the number of characters. lo only moves right and hi only moves left, so together they take at most about n steps before they meet. Each vowel test looks through a fixed string of 10 letters.
  • Space: O(n), for the char array. A Java String cannot be changed, so toCharArray() copies all n characters to have somewhere to swap them.

Without the vowel test, the same two pointers reverse the whole string: see Reverse String.