Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).
Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows:
Examples:
Input : 3 3 4 2 4 4 2 4 4 Output : 4 Input : 3 3 4 2 4 4 2 4 Output : NONE
We have existing solution for this problem please refer Majority Element link. We can solve this problem quickly in Python using Counter(iterable) function. Approach is simple,
- Convert given list of elements into dictionary using Counter() method, having elements as keys and their frequencies as value.
- Now traverse complete dictionary and check for element whose frequency follows the condition greater than (n/2) where n is size of list. That element will be majority element.
# Function to find majority element from collections import Counter def majority(arr): # convert array into dictionary freqDict = Counter(arr) # traverse dictionary and check majority element size = len(arr) for (key,val) in freqDict.items(): if (val > (size/2)): print(key) return print('None') # Driver program if __name__ == "__main__": arr = [3,3,4,2,4,4,2,4,4] majority(arr) |
Output:
4
Recommended Posts:
- Python dictionary, set and counter to check if frequencies can become same
- Dictionary and counter in Python to find winner of election
- Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
- Python | Minimum number of subsets with distinct elements using Counter
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Building a terminal based online dictionary with Python and bash
- Get() method for dictionaries in Python
- Generate a graph using Dictionary in Python
- Packing and Unpacking Arguments in Python
- Dictionary Methods in Python | Set 1 (cmp(), len(), items()...)
- Dictionary Methods in Python | Set 2 (update(), has_key(), fromkeys()...)
- Handling missing keys in Python dictionaries
- Output of Python programs | Set 9 (Dictionary)
- Ways to sort list of dictionaries by values in Python - Using lambda function
- Ways to sort list of dictionaries by values in Python – Using itemgetter
- Python Dictionary Comprehension
- K’th Non-repeating Character in Python using List Comprehension and OrderedDict
- Print anagrams together in Python using List and Dictionary
- Python | Check order of character in string using OrderedDict( )
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

