Write a program to find the majority element in an array in Python
Problem : Find the majority element in an array. An element that dominates in array A[] with array size n is the element that occurs more than n/2 times.
Example :
Input : {3, 3, 4, 2, 4, 4, 2, 4, 4} Output : 4 Giải thích: Tần suất xuất hiện của 4 là 5 lớn hơn một nửa kích thước của mảng. Input : {3, 3, 4, 2, 4, 4, 2, 4} Output : Không có phần tử chiếm đa số Giải thích: Không có phần tử nào có tần suất xuất hiện lớn hơn một nửa kích thước của mảng.
In this article, TipsMake.com will learn with you how to write a program to determine the majority element in the Python programming language.
Method 1: The simplest way to handle it
The most basic solution is to use two loops to count the maximum number of occurrences of all different elements. If the maximum number of occurrences is greater than n/2, stop the loop and return the element with the maximum number of occurrences. If the maximum number of occurrences is not greater than n/2 then the majority element does not exist.
Illustrated solution:
arr[] = {3, 4, 3, 2, 4, 4, 4, 4}, n = 8 For i = 0: count = 0 - Lặp qua toàn bộ mảng, khi một phần tử bằng với arr[i] (là 3), tăng count - count của arr[i] là 2, số này nhỏ hơn n/2, do vậy nó không phải là phần tử chiếm đa số For i = 1: count = 0 - Lặp qua toàn bộ mảng, khi một phần tử bằng với arr[i] (là 4), tăng count - count của arr[i] là 5, số này lớn hơn n/2 (là 4), do vậy nó chính là phần tử chiếm đa số Kết luận, 4 là phần tử chiếm đa số.
Follow the steps below to resolve the issue:
- Create a variable to store the maximum count, count = 0.
- Browse the table from start to finish.
- With an element in the array, run another loop to find the frequency of occurrence of similar elements in the given array.
- If the count is greater than the maximum, update the maximum count and store the index in another variable.
- If the maximum frequency is greater than half the size of the array, print the element. Otherwise, returns the message that the array has no majority element.
Here is the sample code for your reference:
# Python3 program to find Majority # element in an array # Function to find Majority # element in an array def findMajority(arr, n): maxCount = 0 index = -1 # sentinels for i in range(n): count = 0 for j in range(n): if(arr[i] == arr[j]): count += 1 # update maxCount if count of # current element is greater if(count > maxCount): maxCount = count index = i # if maxCount is greater than n/2 # return the corresponding element if (maxCount > n//2): print(arr[index]) else: print("No Majority Element") # Driver code if __name__ == "__main__": arr = [1, 1, 2, 1, 3, 5, 1] n = len(arr) # Function calling findMajority(arr, n) # This code is contributed # by ChitraNayal
Method 2: Use a binary search tree (BST)
Add each element to the BTS and if that element is present, increment the node count. At any stage, if the count of a node is greater than n/2 then print the element.
Follow the steps below to resolve the issue:
- Create a binary search tree, if the same element is entered in the binary search tree, the node frequency will be increased.
- Traverse the array and add the element to the binary search tree.
- If the maximum frequency value of any node is greater than half the size of the array, perform an in-order traversal and find that node.
- Otherwise, returns the array message without the majority element.
Here is the sample code for your reference:
# Python3 program to demonstrate insert operation in binary # search tree. # class for creating node class Node(): def __init__(self, data): self.data = data self.left = None self.right = None self.count = 1 # count of number of times data is inserted in tree # class for binary search tree # it initialises tree with None root # insert function inserts node as per BST rule # and also checks for majority element # if no majority element is found yet, it returns None class BST(): def __init__(self): self.root = None def insert(self, data, n): out = None if (self.root == None): self.root = Node(data) else: out = self.insertNode(self.root, data, n) return out def insertNode(self, currentNode, data, n): if (currentNode.data == data): currentNode.count += 1 if (currentNode.count > n//2): return currentNode.data else: return None elif (currentNode.data < data): if (currentNode.right): self.insertNode(currentNode.right, data, n) else: currentNode.right = Node(data) elif (currentNode.data > data): if (currentNode.left): self.insertNode(currentNode.left, data, n) else: currentNode.left = Node(data) # Driver code # declaring an array arr = [3, 2, 3] n = len(arr) # declaring None tree tree = BST() flag = 0 for i in range(n): out = tree.insert(arr[i], n) if (out != None): print(arr[i]) flag = 1 break if (flag == 0): print("No Majority Element")
Method 3: Use Moore's Voting algorithm
This is a 2 step process:
- The first step gives the element that can be the majority element in the array. If there is a majority element in the array then this step will definitely return the element with the majority. Otherwise, it returns the candidate for the majority element.
- The second step is to check whether the majority element obtained from the previous step is really the majority element. This step is necessary because there exists a case where there is no majority element.
Illustrated solution:
arr[] = {3, 4, 3, 2, 4, 4, 4, 4}, n = 8 maj_index = 0, count = 1 Ở i = 1: arr[maj_index] != arr[i] - count = count – 1 = 1 – 1 = 0 - now count == 0 then: - maj_index = i = 1 - count = count + 1 = 0 + 1 = 1 Ở i = 2: arr[maj_index] != arr[i] - count = count – 1 = 1 – 1 = 0 - now count == 0 then: - maj_index = i = 2 - count = count + 1 = 0 + 1 = 1 Ở i = 3: arr[maj_index] != arr[i] - count = count – 1 = 1 – 1 = 0 - now count == 0 then: - maj_index = i = 3 - count = count + 1 = 0 + 1 = 1 Ở i = 4: arr[maj_index] != arr[i] - count = count – 1 = 1 – 1 = 0 - now count == 0 then: - maj_index = i = 4 - count = count + 1 = 0 + 1 = 1 Ở i = 5: arr[maj_index] == arr[i] - count = count + 1 = 1 + 1 = 2 Ở i = 6: arr[maj_index] == arr[i] - count = count + 1 = 2 + 1 = 3 Ở i = 7: arr[maj_index] == arr[i] - count = count + 1 = 3 + 1 = 4 Do đó, arr[maj_index] có khả năng là ứng viên phần tử chiếm đa số. Bây giờ, duyệt lại toàn bộ mảng để kiểm tra xem arr[maj_index] có phải là phần tử chiếm đa số hay không. arr[maj_index] là 4 4 xuất hiện 5 lần trong mảng nên 4 là phần tử chiếm đa số.
Follow the steps below to resolve the issue:
- Iterates over each element and maintains the count of the majority element (count) and the majority index maj_index.
- If the next element is similar then increase count and if the next element is not similar then decrease count.
- If count is 0, then change maj_index to the current element and set count back to 1.
- Now continue to traverse the array and find the count of the found majority element.
- If count is more than half the array size, return the element.
- Otherwise, returns an array without a majority element.
Here is the sample code for your reference:
# Program for finding out majority element in an array # Function to find the candidate for Majority def findCandidate(A): maj_index = 0 count = 1 for i in range(len(A)): if A[maj_index] == A[i]: count += 1 else: count -= 1 if count == 0: maj_index = i count = 1 return A[maj_index] # Function to check if the candidate occurs more than n/2 times def isMajority(A, cand): count = 0 for i in range(len(A)): if A[i] == cand: count += 1 if count > len(A)/2: return True else: return False # Function to print Majority Element def printMajority(A): # Find the candidate for Majority cand = findCandidate(A) # Print the candidate if it is Majority if isMajority(A, cand) == True: print(cand) else: print("No Majority Element") # Driver code A = [1, 3, 3, 1, 2] # Function call printMajority(A)
Method 4: Use Hashing
In a Hashtable (key-value pair), at value maintains the count for each element (key) and whenever count is greater than half the length of the array, returns that key (the element that is the majority).
Illustrated solution:
arr[] = {3, 4, 3, 2, 4, 4, 4, 4}, n = 8 Tạo một hashtable cho mảng 3 -> 2 4 -> 5 2 -> 1 Duyệt qua toàn bộ hashtable - Count cho 3 là 2, nhỏ hơn n/2 (4) do vậy nó không thể là phần tử chiếm đa số. - Count cho 4 là 5, lớn hơn n/2 (4) do vậy 4 là phần tử chiếm đa số. Kết luận 4 là phần tử chiếm đa số.
Follow these steps to resolve the issue:
- Create a hashtable containing key-value pairs. In this case key is the element while value is the frequency of occurrence of that element in the array.
- Traverse the entire array from beginning to end.
- For each element in the array, add the element to the hashtable if the element does not already exist as a key, otherwise load the value of the key (array[i]) and increment the value by 1.
- If count is greater than half of the array size, return the majority element and terminate the program.
- If not, return the message that the majority element was not found.
Here is the sample code for your reference:
# Python3 program for finding out majority # element in an array def findMajority(arr, size): m = {} for i in range(size): if arr[i] in m: m[arr[i]] += 1 else: m[arr[i]] = 1 count = 0 for key in m: if m[key] > size / 2: count = 1 print("Majority found :-",key) break if(count == 0): print("No Majority element") # Driver code arr = [2, 2, 2, 2, 5, 5, 2, 3, 3] n = len(arr) # Function calling findMajority(arr, n) # This code is contributed by ankush_953
Method 5: Use Sorting
The idea of this method is to rearrange the array. Sorting causes similar elements in the array to be contiguous so iterate over the array and update the count until the current element is still the same as the previous one. If the frequency of an element is greater than half the size of the array, return the element that has the majority.
Illustrated solution:
arr[] = {3, 4, 3, 2, 4, 4, 4, 4}, n = 8 Mảng sau khi Sorting => arr[] = {2, 3, 3, 4, 4, 4, 4, 4}, count = 1 Ở i = 1: - arr[i] != arr[i – 1] => arr[1] != arr[0] - count không lớn hơn n/2, do đó thiết lập lại count, count = 1 Ở i = 2: - arr[i] == arr[i – 1] => arr[2] == arr[1] = 3 - count = count + 1 = 1 + 1 = 2 Ở i = 3 - arr[i] != arr[i – 1] => arr[3] != arr[2] - count không lớn hơn n/2, do đó thiết lập lại count, count = 1 Ở i = 4 - arr[i] == arr[i – 1] => arr[4] == arr[3] = 4 - count = count + 1 = 1 + 1 = 2 Ở i = 5 - arr[i] == arr[i – 1] => arr[5] == arr[4] = 4 - count = count + 1 = 2 + 1 = 3 Ở i = 6 - arr[i] == arr[i – 1] => arr[6] == arr[5] = 4 - count = count + 1 = 3 + 1 = 4 Ở i = 7 - arr[i] == arr[i – 1] => arr[7] == arr[6] = 4 - count = count + 1 = 4 + 1 = 5 Do count của 4 lớn hơn n/2 nên 4 là phần tử chiếm đa số.
Follow these steps to resolve the issue:
- Sort the array and create a variable count and temp with temp = INT_MIN.
- Iterate over all elements from beginning to end.
- If the current element is equal to the previous element, increment count.
- Otherwise, set count back to 1.
- If count is more than half the size of the array, return the majority element and stop the program.
- If not, return the message that there is no majority element.
Here is the sample code for your reference:
# Python3 program to find Majority # element in an array # Function to find Majority element # in an array # it returns -1 if there is no majority element def majorityElement(arr, n) : # sort the array in O(nlogn) arr.sort() count, max_ele, temp, f = 1, -1, arr[0], 0 for i in range(1, n) : # increases the count if the same element occurs # otherwise starts counting new element if(temp == arr[i]) : count += 1 else : count = 1 temp = arr[i] # sets maximum count # and stores maximum occurred element so far # if maximum count becomes greater than n/2 # it breaks out setting the flag if(max_ele < count) : max_ele = count ele = arr[i] if(max_ele > (n//2)) : f = 1 break # returns maximum occurred element # if there is no such element, returns -1 if f == 1 : return ele else : return -1 # Driver code arr = [1, 1, 2, 1, 3, 5, 1] n = len(arr) # Function calling print(majorityElement(arr, n)) # This code is contributed by divyeshrabadiya07
TipsMake.com hopes that this article will be useful to you.
You should read it
- How to set up Python to program on WSL
- Write a program to check duplicate values in Python
- Why should you learn Python programming language?
- 5 choose the best Python IDE for you
- Python online editor
- What is Python? Why choose Python?
- Write a program to find duplicate values in Python
- The next () function in Python
- Array in Python
- Write a program to find missing numbers in a sorted list using Python
- Write a program to calculate the square root of a number in Python
- Learn the first Python program
Maybe you are interested
How to set up a secure guest account on a Windows computer
Norway becomes the first country to have more electric cars than gasoline cars, why?
How to transfer data between 2 Google Drive accounts
Instructions for installing and registering a Steam account on your computer
Windows 11 has added new Timer and Countdown clock widgets, what's noteworthy?
How to change your Google account profile picture