DEV Community

Cover image for Problem 9: Most Frequent Element
Vicente G. Reyes
Vicente G. Reyes

Posted on • Originally published at blog.vicentereyes.org

Problem 9: Most Frequent Element

Hey everyone! πŸ‘‹

Today, we're looking at a common problem in data processing: finding the Most Frequent Element in a list.

The Problem

The goal is to write a function that identifies which element appears most often in a given list. If there's a tie, our implementation will return the first element encountered with that maximum frequency.

Example:

  • most_frequent([1, 1, 1, 2, 2, 3]) should return 1
  • most_frequent(['a', 'b', 'b', 'c']) should return 'b'

The Solution

Here is the Python implementation:

def most_frequent(lst):
    """
    Finds the most frequently occurring element in a list.
    """
    if len(lst) == 0:
        return None

    frequency = {}
    for element in lst:
        if element in frequency:
            frequency[element] += 1
        else:
            frequency[element] = 1

    max_count = 0
    most_frequent_element = None

    for element, count in frequency.items():
        if count > max_count:
            max_count = count
            most_frequent_element = element

    return most_frequent_element

# Test cases
print(most_frequent([1, 1, 1, 2, 2, 3]))  # Output: 1
print(most_frequent(['a', 'b', 'b', 'c']))  # Output: 'b'
Enter fullscreen mode Exit fullscreen mode

Code Breakdown

Let's walk through the logic:

  1. if len(lst) == 0: return None

    • Handles the edge case of an empty list by returning None.
  2. frequency = {}

    • Initializes an empty dictionary to store each element and its corresponding count.
  3. Frequency Counting Loop:

    for element in lst:
        if element in frequency:
            frequency[element] += 1
        else:
            frequency[element] = 1
    
*   Iterates through the input list. If an element is already in the dictionary, we increment its value; otherwise, we add it with a starting count of `1`.
Enter fullscreen mode Exit fullscreen mode
  1. Finding the Maximum:

    max_count = 0
    most_frequent_element = None
    
    for element, count in frequency.items():
        if count > max_count:
            max_count = count
            most_frequent_element = element
    
*   We iterate through the dictionary's items. If the count of the current element is higher than our max_count, we update both max_count and most_frequent_element.
Enter fullscreen mode Exit fullscreen mode




Example Walkthrough with [1, 1, 1, 2, 2, 3]

  1. Counting Phase:

    • 1 encountered -> frequency = {1: 1}
    • 1 encountered -> frequency = {1: 2}
    • 1 encountered -> frequency = {1: 3}
    • 2 encountered -> frequency = {1: 3, 2: 1}
    • 2 encountered -> frequency = {1: 3, 2: 2}
    • 3 encountered -> frequency = {1: 3, 2: 2, 3: 1}
  2. Finding Max Phase:

    • Checking (1, 3): 3 > 0 -> max_count = 3, most_frequent = 1
    • Checking (2, 2): 2 is not > 3 -> No change.
    • Checking (3, 1): 1 is not > 3 -> No change.
  3. Result: Returns 1.


Happy coding! πŸ’»

Top comments (0)