Given a string, sort it in descending order.
Input : alkasingh Output : snlkihgaa Input : nupursingh Output : uusrpnnihg Input : geeksforgeeks Output : ssrokkggfeeee
A simple solution is to use library sort function std::sort()
The time complexity is : O(n log n)
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 ‘z’ to ‘a’ 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 Prabhat kumar singh. 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.
- Stable sort for descending order
- Sort prime numbers of an array in descending order
- Sorting Vector of Pairs in C++ | Set 2 (Sort in descending order by first and second)
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Sort first k values in ascending order and remaining n-k values in descending order
- Sort first half in ascending and second half in descending order | Set 2
- Sort first half in ascending and second half in descending order | 1
- Sorting rows of matrix in descending order followed by columns in ascending order
- Sorting rows of matrix in ascending order followed by columns in descending order
- Sort a string according to the order defined by another string
- Sort an array of string of dates in ascending order
- Sort the array of strings according to alphabetical order defined by another string
- Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)
- Sort a linked list that is sorted alternating ascending and descending orders?
- Sort a Matrix in all way increasing order