Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to sort all vowels at beginning then the consonants, are in sorted order in Python
Suppose we have a lowercase alphabet string s, we have to find a string with all the vowels of s in sorted sequence followed by all consonants of s in sorted sequence.
So, if the input is like "helloworld", then the output will be "eoodhlllrw", as vowels are "eooo" in sorted order and consonants are "dhlllrw" in sorted order.
Algorithm
To solve this, we will follow these steps ?
- vowel_str := blank string, consonant_str := blank string
- for each character c in s, do
- if c is a vowel, then
- vowel_str := vowel_str concatenate c
- otherwise,
- consonant_str := consonant_str concatenate c
- if c is a vowel, then
- return (vowel_str after sorting concatenated with consonant_str after sorting)
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, s):
vowels = 'aeiou'
vowel_str = ''
consonant_str = ''
for c in s:
if c in vowels:
vowel_str = vowel_str + c
else:
consonant_str = consonant_str + c
vowel_str = ''.join(sorted(vowel_str))
consonant_str = ''.join(sorted(consonant_str))
return vowel_str + consonant_str
ob = Solution()
print(ob.solve("helloworld"))
eoodhlllrw
Alternative Approach Using List Comprehension
We can also solve this problem using a more concise approach with list comprehension ?
def sort_vowels_consonants(s):
vowels = 'aeiou'
# Separate vowels and consonants
vowel_chars = [c for c in s if c in vowels]
consonant_chars = [c for c in s if c not in vowels]
# Sort both lists and join
sorted_vowels = ''.join(sorted(vowel_chars))
sorted_consonants = ''.join(sorted(consonant_chars))
return sorted_vowels + sorted_consonants
# Test the function
test_string = "helloworld"
result = sort_vowels_consonants(test_string)
print(f"Input: {test_string}")
print(f"Output: {result}")
Input: helloworld Output: eoodhlllrw
How It Works
The algorithm works by:
- Iterating through each character in the input string
- Separating vowels (a, e, i, o, u) and consonants into different collections
- Sorting both collections alphabetically
- Concatenating sorted vowels first, followed by sorted consonants
Conclusion
This approach efficiently separates vowels and consonants, sorts them individually, and combines them. The time complexity is O(n log n) due to sorting, where n is the length of the string.
