VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-vowels-given-string/

⇱ Reverse vowels in a given string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse vowels in a given string

Last Updated : 17 Mar, 2025

Given a string s, reverse only the vowels in s while keeping the other characters in their original positions.

Examples:

Input: "geeksforgeeks"
Output: "geeksforgeeks"
Explanation: The vowels 'e', 'e', 'o', 'e', 'e' are reversed, resulting in "geeksforgeeks".

Input: "helloworld"
Output: "hollowerld"
Explanation: The vowels 'e', 'o', 'o' are reversed, resulting in "hollowerld".

Input: "programming"
Output: "prigrammong"
Explanation: The vowels 'o', 'a', 'i' are reversed, resulting in "prigrammong".

[Brute-Force Approach] Store and Replace Vowels - O(n) Time and O(n) Space

The idea is to extract all vowels from the given string s and store them in vowelStr while maintaining their order. Then, we iterate through s again, replacing each vowel with the last stored vowel from vowelStr, effectively reversing their positions. This approach works because only vowels are modified, while consonants remain in place.

Below is the implementation of the above approach:


Output
geeksforgeeks

Time Complexity: O(n), as first pass collects vowels, second pass replaces them in reverse order, and each pass costs O(n).
Space Complexity:O(n), as extra space is used to store vowels separately.

[Expected Approach] Using Two Pointers - O(n) Time and O(1) Space

The idea is to use the Two Pointers technique to efficiently reverse only the vowels in the string while keeping other characters in place. We maintain left and right pointers, moving them inward until they find a vowel. Once both pointers point to vowels, we swap them.

Steps to implement the above idea:

  • Initialize left at the start and right at the end of the string to track vowel positions.
  • Use a while loop to iterate until left is smaller than right, ensuring all vowels are processed.
  • Move left forward until a vowel is found, skipping non-vowel characters efficiently.
  • Move right backward until a vowel is found, ensuring only vowels are considered for swapping.
  • If both left and right point to vowels, swap them to reverse their order.
  • Increment left and decrement right to continue checking remaining characters in the string.
  • Return the modified string after all vowels have been reversed while maintaining original positions.

Below is the implementation of the above approach:


Output
geeksforgeeks

Time Complexity: O(n), as each character is processed at most once.
Space Complexity: O(1), since only a few extra variables are used.

Comment
Article Tags: