Reverse vowels in a string

Posted: 11 Mar, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You are given a string 'S'. Your task is to reverse the vowels in the string while keeping the consonants unchanged.

Note:

The alphabets 'a', 'e', 'i', 'o', and 'u' are vowels, while all the remaining alphabets are consonants.
Input Format
The first line of input contains an integer 'T' representing the number of test cases.

The first and the only line of each test case contains the string 'S'.
Output Format:
For each test case, return the string after reversing all its vowels. 
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= |S| <= 10^5 

All characters of string S are lowercase alphabets only.

Where '|S|' denotes the length of string 'S'.

Time limit: 1 sec
Approach 1

The idea is to store all the vowels present in the string in another string while maintaining their respective order. After storing all the vowels in a string, we will reverse that string so that the order of all the vowels gets reversed. After that, we will iterate through the original string and replace all the vowels in the string in the order that they appear in the other string while keeping the consonants unchanged. 

 

Steps: 

  1. Let ‘VOWELS’ be a string that store all the vowels present in string ‘S’.
  2. Iterate through ‘i’ = 0 to S.length( ) - 1 
    • If S[i] is a vowel, then add S[i] to the end of string ‘VOWELS’.
  3. Reverse the string ‘VOWELS’ so that the order of all the vowels gets reversed.
  4. Let ‘j’ be a pointer to the string ‘VOWELS’. Initialize ‘j’ as 0.
  5. Iterate through ‘i’ = 0 to S.length( ) - 1
    • If S[i] is a vowel, then replace S[i] with VOWELS[j] and increase ‘j’ by 1.
  6. Return the modified string ‘S’.
Try Problem