Open In App

Python | Find most common element in a 2D list

Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D list (may or may not be of same length), write a Python program to find the most common element in the given 2D list. 

Examples:

Input : [[10, 20, 30], [20, 50, 10], [30, 50, 10]]
Output : 10

Input : [['geeks', 'wins'], ['techie', 'wins']]
Output : wins

Approach #1 : Using max() function First Pythonic approach is to use max() method of Python. We first flatten the 2D list and then simply apply max() method to find out the maximum occurring element among all the elements. 

Python3




# Python3 program to find most
# common element in a 2D list
 
def mostCommon(lst):
    flatList = [el for sublist in lst for el in sublist]
    return max(flatList, key = flatList.count)
             
# Driver code
lst = [[10, 20, 30], [20, 50, 10], [30, 50, 10]]
print(mostCommon(lst))


Output:

10

There is another method to flatten the list i.e chain.from_iterable() which gives rise to an alternative approach. 

Python3




# Python3 program to find most
# common element in a 2D list
from itertools import chain
 
def mostCommon(lst):
    flatList = list(chain.from_iterable(lst))
    return max(flatList, key=flatList.count)
 
# Driver code
lst = [[10, 20, 30], [20, 50, 10], [30, 50, 10]]
print(mostCommon(lst))


Output:

10

  Approach #2 : Using most_common() from collections module most_common() is used to produce a sequence of the n most frequently encountered input values. Therefore, we simply flatten the list and find the most common element using above mentioned method. 

Python3




# Python3 program to find most
# common element in a 2D list
from itertools import chain
from collections import Counter
 
def mostCommon(lst):
    flatList = chain.from_iterable(lst)
    return Counter(flatList).most_common(1)[0][0]
             
# Driver code
lst = [[10, 20, 30], [20, 50, 10], [30, 50, 10]]
print(mostCommon(lst))


Output:

10

#Approach 3:

The most_common_element() function takes a 2D list as input and returns the most common element in the list. 

In this example, we define a 2D list lst and pass it to the most_common_element() function. The function counts the occurrences of each element in the list and returns the most common element, which is 2 in this case. Finally, we print the most common element to the console.

Note that if there are multiple elements with the same maximum count, the max() function will return one of them arbitrarily. If you need to find all the most common elements, you can iterate over the dictionary and check which keys have the maximum value.

Approach:

1.Create an empty dictionary count_dict to keep track of the count of each element.
2.Traverse through each element in the 2D list using two nested loops.
3.For each element, check if it is already present in the count_dict dictionary.
4.If the element is present, increment its count by 1.
5.If the element is not present, add it to the dictionary with a count of 1.
6.After all elements have been counted, find the key with the highest count in the dictionary using the max() function and the key argument set to count_dict.get.
7.Return the key with the highest count.

Python3




def most_common_element(lst):
    """
    Returns the most common element in a 2D list.
    """
    count_dict = {}
    # Traverse through each element in the list and keep track of the count of each element
    for row in lst:
        for elem in row:
            if elem in count_dict:
                count_dict[elem] += 1
            else:
                count_dict[elem] = 1
    # Find the key with the highest count in the dictionary and return it
    return max(count_dict, key=count_dict.get)
 
# Example usage
lst = [
    [1, 2, 3],
    [2, 2, 2],
    [3, 3, 1]
]
most_common = most_common_element(lst)
print(most_common)  # Output: 2


Output

2

# Time complexity: O(M*N), where M is the number of rows and N is the number of columns in the list.
# The function traverses through each element in the list once.
# For each element, the function performs a constant amount of work, which takes O(1) time.
# Therefore, the total time complexity of the function is O(M*N).

# Auxiliary Space: O(K), where K is the number of unique elements in the list.
# The function uses a dictionary to store the count of each element, which takes O(K) space.
# The function also uses a constant amount of space for variables and function calls, which takes O(1) space.
# Therefore, the total space complexity of the function is O(K).

Approach #4: Using numpy module

Algorithm:

Create two arrays, “values” and “counts”, using the np.unique() function on the input array “arr”. The “values” array contains the unique values in “arr” and the “counts” array contains the frequency of each unique value in “arr”.
Find the index of the maximum value in the “counts” array using the np.argmax() function.
Return the value at the index found in step 2 in the “values” array.

Python




import numpy as np
 
def mostCommon(arr):
    values, counts = np.unique(arr, return_counts=True)
    index = np.argmax(counts)
    return values[index]
#DRIVER CODE
lst = np.array([[10, 20, 10], [30, 40, 10], [50, 10, 30]])
print(mostCommon(lst)) # Output: 10


Time complexity:
The time complexity of the np.unique() function is O(nlogn), where n is the size of the input array. The time complexity of the np.argmax() function is O(n), where n is the size of the input array. Therefore, the overall time complexity of the algorithm is O(nlogn + n), which simplifies to O(nlogn).

Auxiliary Space:
The space complexity of the algorithm is O(n), where n is the size of the input array. This is because the np.unique() function creates two arrays of size n, “values” and “counts”, to store the unique values and their frequency. The np.argmax() function uses constant space. Therefore, the overall space complexity of the algorithm is O(n).



Last Updated : 09 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads