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 consonat 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.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.