Lexicographically first alternate vowel and consonant string
Given a string str. The problem is to rearrange characters of the given string such that the vowels and consonants occupy alternate position and the string so formed should be lexicographically (alphabetically) smallest. If string can not be rearranged in desired way, print “no such string”.
Input : mango Output : gamon It could be arranged in other ways too, like manog, etc., but gamon is lexicographically smallest. Input : aeroplane Output : alanepero
Approach: Following are the steps:
- Store frequency of each character of input string in a hash table.
- Count number of vowels and consonants in given string.
- If difference between counts is more than one, return “Not Possible”.
- Else, form separate vowel and consonant strings with the help of the hash table having frequencies of each character of the input string. Note, while creating vowel and consonant strings, the characters in respective strings should be in alphabetical order.
- If there are more vowels than consonants, print first vowel first and then print remaining characters from consonant and vowel strings alternately.
- If there are more consonants than vowels, print first consonant first and then print remaining characters from vowel and consonant strings alternately.
- If counts are same, compare first vowel with first consonant and print the smaller one first and then continue printing alternately.
Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(26).
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.