<AI/>
enru
All posts

Reverse vowels of a string

LeetCode 345: Reverse only the vowels of a string using two pointers.

Difficulty
Easy
Published
Topics
#string#two pointers
Open on LeetCode

Problem Description

You are given a string s. Write a function that reverses all the vowels in it and returns the new string.

The vowels are a, e, i, o and u, and they can appear in both lower and upper case.

Constraints

  • The string contains from 1 to 3 * 105 characters
  • The string consists of printable ASCII characters
  • Characters can be in upper or lower case

Examples

Input: hello

Answer: holle

Solution

First of all, we need a way to tell in constant time whether a given letter is a vowel. For this we create a structure listing all possible vowels in both cases.

typescript
const dict = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);

By the way, we list the letters in both cases at once so that we don't have to lowercase every character of the string before comparing it. This saves a bit of time.

Now let's implement the reversal itself. We need two pointers:

  • leftIdx equals zero
  • rightIdx equals the index of the last character of the string

We move the left and right pointers in turn until each of them points to a vowel. As soon as that happens, we swap the letters and repeat the process while leftIdx < rightIdx.

typescript
export const reverseVowels = (s: string): string => {
  const dict = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
 
  let leftIdx = 0;
  let rightIdx = s.length - 1;
 
  const chars = [...s];
 
  while (leftIdx < rightIdx) {
    const left = chars[leftIdx];
    const right = chars[rightIdx];
 
    if (!dict.has(left)) {
      leftIdx++;
    } else if (!dict.has(right)) {
      rightIdx--;
    } else {
      const tmp = chars[leftIdx];
      chars[leftIdx] = chars[rightIdx];
      chars[rightIdx] = tmp;
      leftIdx++;
      rightIdx--;
    }
  }
 
  return chars.join('');
};

Complexity Analysis

Time Complexity

Since we go over all characters once, the complexity is O(n).

Space Complexity

Converting the string into an array creates a new variable, so the space complexity is linear: O(n).