![]() |
VOOZH | about |
Given String list, perform sort operation on basis of frequency of particular character.
Input : test_list = ["geekforgeekss", "is", "bessst", "for", "geeks"], K = 's'
Output : ['bessst', 'geekforgeekss', 'geeks', 'is', 'for']
Explanation : bessst has 3 occurrence, geeksforgeekss has 3, and so on.Input : test_list = ["geekforgeekss", "is", "bessst"], K = 'e'
Output : ["geekforgeekss", "bessst", "is"]
Explanation : Ordered decreasing order of 'e' count.
Method #1 : Using sorted() + count() + lambda
In this, sorted() is used to perform task of sort, count() is as function upon which sorting is to be performed. using additional key param, and function encapsulation used is lambda.
The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']
Time Complexity: O(nlogn), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using sort() + count() + lambda
In this, we perform task of sort using sort(), this is similar to above, only difference being that sorting is done inplace.
The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using operator.countOf() method
The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']
Time Complexity: O(NLogN)
Auxiliary Space: O(N)
Method 4: Using heapq.nlargest() and count()
Step-by-step approach:
Sorted String: ['geekforgeeks', 'geeks', 'best', 'is', 'for']
Time complexity: O(n*log(n)) for sorting the list of strings.
Auxiliary space: O(n) for storing the list of strings.