Skip to main content

Reverse Vowels of a String Solution

In this tutorial, we will solve the Reverse Vowels of a String problem using efficient string manipulation techniques. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++.

Problem Description​

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

The vowels are 'a', 'e', 'i', 'o', 'u', and they can appear in both lower and upper cases, more than once.

Examples​

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

Constraints​

  • 1 <= s.length <= 3 * 10^5
  • s consists of printable ASCII characters.

Solution for Reverse Vowels of a String​

Intuition and Approach​

To solve this problem, we can use a two-pointer approach to efficiently reverse the vowels in the string. We will place one pointer at the beginning (left) and another at the end (right) of the string. We will move these pointers towards each other, swapping vowels when both pointers point to a vowel.

Approach: Two Pointers​

We can use two pointers to efficiently reverse the vowels in the string. This involves traversing the string from both ends and swapping vowels when encountered.

Implementation​

Live Editor
function reverseVowels(s) {
  const vowels = new Set('aeiouAEIOU');
  const arr = s.split('');
  let left = 0;
  let right = arr.length - 1;

  while (left < right) {
    if (!vowels.has(arr[left])) {
      left++;
      continue;
    }
    if (!vowels.has(arr[right])) {
      right--;
      continue;
    }
    [arr[left], arr[right]] = [arr[right], arr[left]];
    left++;
    right--;
  }

  return arr.join('');
}

const input = "hello";
const result = reverseVowels(input);

return (
  <div>
    <p>
      <b>Input:</b> {input}
    </p>
    <p>
      <b>Output:</b> {result}
    </p>
  </div>
);
Result
Loading...

Codes in Different Languages​

Written by @aryansh-patel
 function reverseVowels(s) {
const vowels = new Set('aeiouAEIOU');
const arr = s.split('');
let left = 0;
let right = arr.length - 1;

while (left < right) {
if (!vowels.has(arr[left])) {
left++;
continue;
}
if (!vowels.has(arr[right])) {
right--;
continue;
}
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}

return arr.join('');
}

Complexity Analysis​

  • Time Complexity: O(n)O(n), where n is the length of the string.

  • Space Complexity: O(1)O(1), as we are not using any additional space.

  • The time complexity is linear in terms of the length of the string. Each character is checked and potentially swapped once, leading to a time complexity of O(n)O(n).

  • The space complexity is constant because we only use a few extra variables regardless of the string size.

Note

This solution efficiently reverses the vowels in the string while maintaining the order of non-vowel characters.


Video Explanation of Reverse Vowels of a String​