Problem

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

Examples

Example 1:

Input : s = hello
Output : holle

Example 2:

Input : s = hello world
Output : hollo werld

Solution

Method 1 - Store the vowels and place them in reverse order

One simple solution is to store all the vowels while scanning the string and placing the vowels in the reverse order in another iteration of string.

Time complexity : O(n) where n = length of string Auxiliary Space : O(v) where v = number of vowels in string

Method 2 - Use 2 pointers

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> vowelSet = new ArrayList<Character>();
	vowelSet.add('a');
	vowelSet.add('e');
	vowelSet.add('i');
	vowelSet.add('o');
	vowelSet.add('u');
	vowelSet.add('A');
	vowelSet.add('E');
	vowelSet.add('I');
	vowelSet.add('O');
	vowelSet.add('U');

	char[] chars = s.toCharArray();

	int left = 0;
	int right = s.length() - 1;

	while (left < right) {
		while (left < right && !vowelSet.contains(chars[left])) {
			left++;
		}

		while (left < right && !vowelSet.contains(chars[right])) {
			right--;
		}

		char temp = chars[left];
		chars[left] = chars[right];
		chars[right] = temp;
		left++;
		right--;

	}

	return new String(chars);
}

Complexity

  • ⏰ Time complexity: O(n)
  • 🧺 Space complexity: O(1)