Python | Find frequency of largest element in list
Given a list, the task is to find the number of occurrences of the largest element of the list.
Examples:
Input : [1, 2, 8, 5, 8, 7, 8]
Output :3
Input : [2, 9, 1, 3, 4, 5]
Output :1
Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list. Below is the implementation.
Python3
L = [ 1 , 2 , 8 , 5 , 8 , 7 , 8 ]
frequency = print (L.count( max (L)))
|
Output:
3
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using collections.Counter()
Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown as 0.
Python3
import collections
L = [ 1 , 2 , 8 , 5 , 8 , 7 , 8 ]
largest = max (L)
res = collections.Counter(L)
print (res[largest])
|
Output:
3
Time Complexity: O(n) where n is the number of elements in the list.
Auxiliary Space: O(1) constant additional space is created.
Method 3: Using the dictionary
In this approach, the number of occurrences of each element is stored in a dictionary as a key-value pair, where key is the element and value is the frequency.
Python3
L = [ 1 , 2 , 8 , 5 , 8 , 7 , 8 ]
d = {}
largest = max (L)
for i in L:
if i in d:
d[i] + = 1
else :
d[i] = 1
print (d[largest])
|
Output:
3
Time Complexity: O(n)
Auxiliary Space: O(n)
Last Updated :
21 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...