Examples :
Input: lst = [’a’,’ a’, ’a’,’ b’, ’b’ , ’c’], k = 2 Output: [’ a’, ’a’,’ a’, ’b’,’ b’] Input: lst = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4], k = 3 Output: [1, 1, 1, 1, 3, 3, 3 ]
Approach # 1: Python naive
Counter ()
from collections module
creates a dictionary which maps values to counters and stores them in & # 39; countted & # 39 ;. We then use temp_lst to store the items to be deleted. Finally, we go through the given list and add any items that are not in & # 39; temp_lst & # 39; to & # 39; res_lst & # 39; containing the required output.
|
Exit:
[’a’,’ a’, ’a’,’ b’, ’b’]
Approach # 2: An Effective Approach
An efficient approach to using the Counter method is to create a dictionary mapping value for the counts and then use a list comprehension to filter out counts that exceed the specified value. This approach is efficient in terms of time and space.
|
Exit:
[’a’,’ a’ , ’a’,’ b’, ’b’]