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.
- Alternate vowel and consonant string
- Print all Subsequences of String which Start with Vowel and End with Consonant.
- Program to find if a character is vowel or Consonant
- Count of adjacent Vowel Consonant Pairs
- Replace every consonant sequence with its length in the given string
- Check if the given string is vowel prime
- Program to count vowels, consonant, digits and special characters in string.
- Python program to check if given string is vowel Palindrome
- Count the nodes of the tree whose weighted string contains a vowel
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Lexicographically next string
- Lexicographically n-th permutation of a string
- Lexicographically first palindromic string