Open In App

Python | Elements with Frequency equal K

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate
# Elements with Frequency equal K
# using naive method
 
# initializing list
test_list = [9, 4, 5, 4, 4, 5, 9, 5]
 
# printing original list
print ("Original list : " + str(test_list))
 
# initializing K
K = 3
 
# using naive method to
# get most frequent element
res = []
for i in test_list:
    freq = test_list.count(i)
    if freq == K and i not in res:
        res.append(i)
     
# printing result
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




# Python3 code to demonstrate
# Elements with Frequency equal K
# using Counter() function
from collections import Counter
 
# initializing list
test_list = [9, 4, 5, 4, 4, 5, 9, 5]
 
# printing original list
print("Original list : " + str(test_list))
 
# initializing K
K = 3
res = []
freq = Counter(test_list)
for key, value in freq.items():
    if(value == K):
        res.append(key)
# printing result
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) 
Auxiliary Space: O(n)

Method #3: Using Operator.countOf() function

Python3




# Python3 code to demonstrate
# Elements with Frequency equal K
 
import operator as op
# initializing list
test_list = [9, 4, 5, 4, 4, 5, 9, 5]
 
# printing original list
print("Original list : " + str(test_list))
 
# initializing K
K = 3
res = []
unique_elements = set(test_list)
for i in unique_elements:
    if op.countOf(test_list, i) == K:
        res.append(i)
# printing result
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)
Auxiliary Space:O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads