[Solved] Sort Characters by Frequency in Python String
This is one of the questions asked in the coding interview. This question looks difficult. But, Python makes it easy, if you have an understanding of basic Python programming.
Problem Statement:
The characters in the string should be sorted based on the following conditions.
- Sort the characters in the string by their frequency of occurrences (the number of times characters have occurred in the string).
- If the two different characters have the same frequency, these letters should be sorted based on their alphabetical order.
Example:
Input String:
csestack
Output String:
aektccss
How to Sort Characters by Frequency in Python?
There are two methods for sorting in Python. Here, we are using sorted() inbuilt Python function for sorting the string.
Here are the steps to follow.
- To fulfill the second condition, let’s sort the string using
sorted()
inbuilt function. - After that, sort the array based on the frequency of the characters. For which we are using
sorted()
function with the key attribute and Python lambda function.
Python Program:
msg_given = 'csestack'
msg_alpha = sorted(msg_given)
sorted_list = sorted(msg_alpha, key=lambda c: msg_alpha.count(c))
final_msg = "".join(sorted_list)
print(final_msg)
Output:
aektccss
Note: sorted()
function returns the list of the characters. We have to convert it back to the string after sorting. For which, we can use join()
operation.
Sometime, in a coding interview, the interviewer may ask you to write your own code for sorting algorithm, instead of using the inbuilt function.
Time Complexity:
Believe, sorted()
function takes O(n log n)
time for string the string, where n
is the length of the string.
For counting each character in the string using count()
function, it takes O(n^2)
time.
The overall time complexity to sort characters by frequency in Python is O(n^2)
.
If you can solve this problem in any another way, share your solution in the comment.