This is one of the most essential operation that programmer quite often comes in terms with. Be it development or competitive programming, this utility is quite essential to master as it helps to perform many tasks that involve this task to be its subtask. Lets discuss approach to achieve this operation.
Method #1 : Naive method As the brute force method, we just count all the elements and then just return the elements whose count equals K. This is the basic method that one could think of executing when faced with this issue.
Python3
test_list = [ 9 , 4 , 5 , 4 , 4 , 5 , 9 , 5 ]
print ( "Original list : " + str (test_list))
K = 3
res = []
for i in test_list:
freq = test_list.count(i)
if freq = = K and i not in res:
res.append(i)
print ( "Elements with count K are : " + str (res))
|
Output : Original list : [9, 4, 5, 4, 4, 5, 9, 5]
Elements with count K are : [4, 5]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using Counter() function
Python3
from collections import Counter
test_list = [ 9 , 4 , 5 , 4 , 4 , 5 , 9 , 5 ]
print ( "Original list : " + str (test_list))
K = 3
res = []
freq = Counter(test_list)
for key, value in freq.items():
if (value = = K):
res.append(key)
print ( "Elements with count K are : " + str (res))
|
OutputOriginal list : [9, 4, 5, 4, 4, 5, 9, 5]
Elements with count K are : [4, 5]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using Operator.countOf() function
Python3
import operator as op
test_list = [ 9 , 4 , 5 , 4 , 4 , 5 , 9 , 5 ]
print ( "Original list : " + str (test_list))
K = 3
res = []
unique_elements = set (test_list)
for i in unique_elements:
if op.countOf(test_list, i) = = K:
res.append(i)
print ( "Elements with count K are : " + str (res))
|
OutputOriginal list : [9, 4, 5, 4, 4, 5, 9, 5]
Elements with count K are : [4, 5]
Time Complexity:O(N)
Auxiliary Space:O(N)