Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a program to print the characters of this string in sorted order.
Input : bbccdefbbaa Output : aabbbbccdef Input : geeksforgeeks Output : eeeefggkkorss
# Python3 program to sort a string
# of characters
# function to print string in
# sorted order
def sortString(str) :
str = ”.join(sorted(str))
# Driver Code
s = “geeksforgeeks”
# This code is contributed by Smitha
Time Complexity: O(n log n), where n is the length of string.
An efficient approach will be to observe first that there can be a total of 26 unique characters only. So, we can store the count of occurrences of all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the hashed array will represent character ‘a’, second will represent ‘b’ and so on. Finally, we will simply traverse the hashed array and print the characters from ‘a’ to ‘z’ the number of times they occurred in input string.
Below is the implementation of above idea:
Time Complexity: O( n ), where n is the length of input string.
Auxiliary Space: O( 1 ).
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Sort string of characters using Stack
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Min flips of continuous characters to make all characters same in a string
- String with k distinct characters and no same characters adjacent
- Minimal moves to form a string by adding characters or appending string itself
- Create a new string by alternately combining the characters of two halves of the string in reverse
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Minimum deletions from string to reduce it to string with at most 2 unique characters
- Find the smallest window in a string containing all characters of another string
- String matching where one string contains wildcard characters
- Check whether second string can be formed from characters of first string
- Remove characters from the first string which are present in the second string
- Sort a string according to the order defined by another string
- Roll the characters of string
- Mirror characters of a string