Tutorialspoint
Problem
Solution
Submissions

Most Frequent Element in a List

Certification: Basic Level Accuracy: 79.49% Submissions: 39 Points: 5

Write a Python program that finds the most frequent element in a list.

Example 1
  • Input: lst = [1, 3, 2, 3, 4, 1, 3]
  • Output: 3
  • Explanation:
    • Step 1: Create a dictionary to count the frequency of each element in the list.
    • Step 2: Element 1 appears twice, add entry {1: 2}.
    • Step 3: Element 3 appears three times, add entry {3: 3}.
    • Step 4: Element 2 appears once, add entry {2: 1}.
    • Step 5: Element 4 appears once, add entry {4: 1}.
    • Step 6: Find the element with the maximum frequency, which is 3.
    • Step 7: Return 3 as the most frequent element.
Example 2
  • Input: lst = [5, 5, 5, 2, 2, 3]
  • Output: 5
  • Explanation:
    • Step 1: Create a dictionary to count the frequency of each element in the list.
    • Step 2: Element 5 appears three times, add entry {5: 3}.
    • Step 3: Element 2 appears twice, add entry {2: 2}.
    • Step 4: Element 3 appears once, add entry {3: 1}.
    • Step 5: Find the element with the maximum frequency, which is 5.
    • Step 6: Return 5 as the most frequent element.
Constraints
  • 1 ≤ len(lst) ≤ 10^5
  • -10^5 ≤ lst[i] ≤ 10^5
  • Time Complexity: O(n) where n is the length of the input list
  • Space Complexity: O(n) to store the frequency dictionary
ListPwCDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the collections.Counter class to count element frequencies.
  • Use the max() function with a custom key to find the most frequent element.
  • Iterate through the list and maintain a frequency map using a dictionary.

Steps to solve by this approach:

 Step 1: Import the Counter class from the collections module.

 Step 2: Create a Counter object from the input list to count element occurrences.
 Step 3: Get the keys from the Counter (the unique elements).
 Step 4: Find the key with the maximum count value using a lambda function.
 Step 5: Return the most frequent element (handling ties by returning the first found).
 Step 6: Handle the case of an empty list by raising an appropriate exception.

Submitted Code :