Write a function which takes an array and prints the majority element (if it exists), otherwise prints “No 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).
Examples :
Input : {3, 3, 4, 2, 4, 4, 2, 4, 4}
Output : 4
Explanation: The frequency of 4 is 5 which is greater
than the half of the size of the array size.
Input : {3, 3, 4, 2, 4, 4, 2, 4}
Output : No Majority Element
Explanation: There is no element whose frequency is
greater than the half of the size of the array size.
Approach: The basic solution is to have two loops and keep track of the maximum count for all different elements. If maximum count becomes greater than n/2 then break the loops and return the element having maximum count. If the maximum count doesn’t become more than n/2 then the majority element doesn’t exist.
Algorithm:
Create a variable to store the max count, count = 0
Traverse through the array from start to end.
For every element in the array run another loop to find the count of similar elements in the given array.
If the count is greater than the max count update the max count and store the index in another variable.
If the maximum count is greater than the half the size of the array, print the element. Else print there is no majority element.
Below is the implementation of the above idea:
C++
// C++ program to find Majority
// element in an array
#include <bits/stdc++.h>
usingnamespacestd;
// Function to find Majority element
// in an array
voidfindMajority(intarr[], intn)
{
intmaxCount = 0;
intindex = -1; // sentinels
for(inti = 0; i < n; i++) {
intcount = 0;
for(intj = 0; j < n; j++) {
if(arr[i] == arr[j])
count++;
}
// 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)
cout << arr[index] << endl;
else
cout << "No Majority Element"<< endl;
}
// Driver code
intmain()
{
intarr[] = { 1, 1, 2, 1, 3, 5, 1 };
intn = sizeof(arr) / sizeof(arr[0]);
// Function calling
findMajority(arr, n);
return0;
}
Java
// Java program to find Majority
// element in an array
importjava.io.*;
classGFG {
// Function to find Majority element
// in an array
staticvoidfindMajority(intarr[], intn)
{
intmaxCount = 0;
intindex = -1; // sentinels
for(inti = 0; i < n; i++) {
intcount = 0;
for(intj = 0; j < n; j++) {
if(arr[i] == arr[j])
count++;
}
// 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)
System.out.println(arr[index]);
else
System.out.println("No Majority Element");
}
// Driver code
publicstaticvoidmain(String[] args)
{
intarr[] = { 1, 1, 2, 1, 3, 5, 1};
intn = arr.length;
// Function calling
findMajority(arr, n);
}
// This code is contributed by ajit.
}
Python3
# Python3 program to find Majority
# element in an array
# Function to find Majority
# element in an array
deffindMajority(arr, n):
maxCount =0
index =-1# sentinels
fori inrange(n):
count =0
forj inrange(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
C#
// C# program to find Majority
// element in an array
usingSystem;
publicclassGFG {
// Function to find Majority element
// in an array
staticvoidfindMajority(int[] arr, intn)
{
intmaxCount = 0;
intindex = -1; // sentinels
for(inti = 0; i < n; i++) {
intcount = 0;
for(intj = 0; j < n; j++) {
if(arr[i] == arr[j])
count++;
}
// 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)
Console.WriteLine(arr[index]);
else
Console.WriteLine("No Majority Element");
}
// Driver code
staticpublicvoidMain()
{
int[] arr = { 1, 1, 2, 1, 3, 5, 1 };
intn = arr.Length;
// Function calling
findMajority(arr, n);
}
// This code is contributed by Tushil..
}
PHP
<?php
// PHP program to find Majority
// element in an array
// Function to find Majority element
// in an array
functionfindMajority($arr, $n)
{
$maxCount= 0;
$index= -1; // sentinels
for($i= 0; $i< $n; $i++)
{
$count= 0;
for($j= 0; $j< $n; $j++)
{
if($arr[$i] == $arr[$j])
$count++;
}
// 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)
echo$arr[$index] . "\n";
else
echo"No Majority Element". "\n";
}
// Driver code
$arr= array(1, 1, 2, 1, 3, 5, 1);
$n= sizeof($arr);
// Function calling
findMajority($arr, $n);
// This code is contributed
// by Akanksha Rai
Javascript
<script>
// Javascript program to find Majority
// element in an array
// Function to find Majority element
// in an array
functionfindMajority(arr, n)
{
let maxCount = 0;
let index = -1; // sentinels
for(let i = 0; i < n; i++)
{
let count = 0;
for(let j = 0; j < n; j++)
{
if(arr[i] == arr[j])
count++;
}
// 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)
document.write(arr[index]);
else
document.write("No Majority Element");
}
// Driver code
let arr = [ 1, 1, 2, 1, 3, 5, 1 ];
let n = arr.length;
// Function calling
findMajority(arr, n);
// This code is contributed by suresh07
</script>
Output
1
Complexity Analysis:
Time Complexity: O(n*n). A nested loop is needed where both the loops traverse the array from start to end, so the time complexity is O(n^2).
Auxiliary Space: O(1). As no extra space is required for any operation so the space complexity is constant.
Approach: Insert elements in BST one by one and if an element is already present then increment the count of the node. At any stage, if the count of a node becomes more than n/2 then return.
Algorithm:
Create a binary search tree, if same element is entered in the binary search tree the frequency of the node is increased.
traverse the array and insert the element in the binary search tree.
If the maximum frequency of any node is greater than the half the size of the array, then perform a inorder traversal and find the node with frequency greater than half
Else print No majority Element.
Below is the implementation of the above idea:
C++14
// C++ program to demonstrate insert operation in binary
// search tree.
#include <bits/stdc++.h>
usingnamespacestd;
structnode {
intkey;
intc = 0;
structnode *left, *right;
};
// A utility function to create a new BST node
structnode* newNode(intitem)
{
structnode* temp
= (structnode*)malloc(sizeof(structnode));
temp->key = item;
temp->c = 1;
temp->left = temp->right = NULL;
returntemp;
}
// A utility function to insert a new node with given key in
Auxiliary Space: O(n). As extra space is needed to store the array in tree.
METHOD 3 (Using Moore’s Voting Algorithm):
Approach: This is a two-step process.
The first step gives the element that maybe the majority element in the array. If there is a majority element in an array, then this step will definitely return majority element, otherwise, it will return candidate for majority element.
Check if the element obtained from the above step is majority element. This step is necessary as there might be no majority element.
Algorithm:
Loop through each element and maintains a count of majority element, and a majority index, maj_index
If the next element is same then increment the count if the next element is not same then decrement the count.
if the count reaches 0 then changes the maj_index to the current element and set the count again to 1.
Now again traverse through the array and find the count of majority element found.
If the count is greater than half the size of the array, print the element
Else print that there is no majority element
Below is the implementation of above idea:
C++
// C++ Program for finding out
// majority element in an array
#include <bits/stdc++.h>
usingnamespacestd;
/* Function to find the candidate for Majority */
intfindCandidate(inta[], intsize)
{
intmaj_index = 0, count = 1;
for(inti = 1; i < size; i++) {
if(a[maj_index] == a[i])
count++;
else
count--;
if(count == 0) {
maj_index = i;
count = 1;
}
}
returna[maj_index];
}
/* Function to check if the candidate
occurs more than n/2 times */
boolisMajority(inta[], intsize, intcand)
{
intcount = 0;
for(inti = 0; i < size; i++)
if(a[i] == cand)
count++;
if(count > size / 2)
return1;
else
return0;
}
/* Function to print Majority Element */
voidprintMajority(inta[], intsize)
{
/* Find the candidate for Majority*/
intcand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if(isMajority(a, size, cand))
cout << " "<< cand << " ";
else
cout << "No Majority Element";
}
/* Driver code */
intmain()
{
inta[] = { 1, 3, 3, 1, 2 };
intsize = (sizeof(a)) / sizeof(a[0]);
// Function calling
printMajority(a, size);
return0;
}
C
/* Program for finding out majority element in an array */
#include <stdio.h>
#define bool int
intfindCandidate(int*, int);
boolisMajority(int*, int, int);
/* Function to print Majority Element */
voidprintMajority(inta[], intsize)
{
/* Find the candidate for Majority*/
intcand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if(isMajority(a, size, cand))
printf(" %d ", cand);
else
printf("No Majority Element");
}
/* Function to find the candidate for Majority */
intfindCandidate(inta[], intsize)
{
intmaj_index = 0, count = 1;
inti;
for(i = 1; i < size; i++) {
if(a[maj_index] == a[i])
count++;
else
count--;
if(count == 0) {
maj_index = i;
count = 1;
}
}
returna[maj_index];
}
/* Function to check if the candidate occurs more than n/2
* times */
boolisMajority(inta[], intsize, intcand)
{
inti, count = 0;
for(i = 0; i < size; i++)
if(a[i] == cand)
count++;
if(count > size / 2)
return1;
else
return0;
}
/* Driver code */
intmain()
{
inta[] = { 1, 3, 3, 1, 2 };
intsize = (sizeof(a)) / sizeof(a[0]);
// Function call
printMajority(a, size);
getchar();
return0;
}
Java
/* Program for finding out majority element in an array */
classMajorityElement {
/* Function to print Majority Element */
voidprintMajority(inta[], intsize)
{
/* Find the candidate for Majority*/
intcand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if(isMajority(a, size, cand))
System.out.println(" "+ cand + " ");
else
System.out.println("No Majority Element");
}
/* Function to find the candidate for Majority */
intfindCandidate(inta[], intsize)
{
intmaj_index = 0, count = 1;
inti;
for(i = 1; i < size; i++) {
if(a[maj_index] == a[i])
count++;
else
count--;
if(count == 0) {
maj_index = i;
count = 1;
}
}
returna[maj_index];
}
/* Function to check if the candidate occurs more
than n/2 times */
booleanisMajority(inta[], intsize, intcand)
{
inti, count = 0;
for(i = 0; i < size; i++) {
if(a[i] == cand)
count++;
}
if(count > size / 2)
returntrue;
else
returnfalse;
}
/* Driver code */
publicstaticvoidmain(String[] args)
{
MajorityElement majorelement
= newMajorityElement();
inta[] = newint[] { 1, 3, 3, 1, 2};
// Function call
intsize = a.length;
majorelement.printMajority(a, size);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Program for finding out majority element in an array
# Function to find the candidate for Majority
deffindCandidate(A):
maj_index =0
count =1
fori inrange(len(A)):
ifA[maj_index] ==A[i]:
count +=1
else:
count -=1
ifcount ==0:
maj_index =i
count =1
returnA[maj_index]
# Function to check if the candidate occurs more than n/2 times
defisMajority(A, cand):
count =0
fori inrange(len(A)):
ifA[i] ==cand:
count +=1
ifcount > len(A)/2:
returnTrue
else:
returnFalse
# Function to print Majority Element
defprintMajority(A):
# Find the candidate for Majority
cand =findCandidate(A)
# Print the candidate if it is Majority
ifisMajority(A, cand) ==True:
print(cand)
else:
print("No Majority Element")
# Driver code
A =[1, 3, 3, 1, 2]
# Function call
printMajority(A)
C#
// C# Program for finding out majority element in an array
usingSystem;
classGFG {
/* Function to print Majority Element */
staticvoidprintMajority(int[] a, intsize)
{
/* Find the candidate for Majority*/
intcand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if(isMajority(a, size, cand))
Console.Write(" "+ cand + " ");
else
Console.Write("No Majority Element");
}
/* Function to find the candidate for Majority */
staticintfindCandidate(int[] a, intsize)
{
intmaj_index = 0, count = 1;
inti;
for(i = 1; i < size; i++) {
if(a[maj_index] == a[i])
count++;
else
count--;
if(count == 0) {
maj_index = i;
count = 1;
}
}
returna[maj_index];
}
// Function to check if the candidate
// occurs more than n/2 times
staticboolisMajority(int[] a, intsize, intcand)
{
inti, count = 0;
for(i = 0; i < size; i++) {
if(a[i] == cand)
count++;
}
if(count > size / 2)
returntrue;
else
returnfalse;
}
// Driver Code
publicstaticvoidMain()
{
int[] a = { 1, 3, 3, 1, 2 };
intsize = a.Length;
// Function call
printMajority(a, size);
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP Program for finding out majority
// element in an array
// Function to find the candidate
// for Majority
functionfindCandidate($a, $size)
{
$maj_index= 0;
$count= 1;
for($i= 1; $i< $size; $i++)
{
if($a[$maj_index] == $a[$i])
$count++;
else
$count--;
if($count== 0)
{
$maj_index= $i;
$count= 1;
}
}
return$a[$maj_index];
}
// Function to check if the candidate
// occurs more than n/2 times
functionisMajority($a, $size, $cand)
{
$count= 0;
for($i= 0; $i< $size; $i++)
if($a[$i] == $cand)
$count++;
if($count> $size/ 2)
return1;
else
return0;
}
// Function to print Majority Element
functionprintMajority($a, $size)
{
/* Find the candidate for Majority*/
$cand= findCandidate($a, $size);
/* Print the candidate if it is Majority*/
if(isMajority($a, $size, $cand))
echo" ", $cand, " ";
else
echo"No Majority Element";
}
// Driver Code
$a= array(1, 3, 3, 1, 2);
$size= sizeof($a);
// Function calling
printMajority($a, $size);
// This code is contributed by jit_t
?>
Output
No Majority Element
Complexity Analysis:
Time Complexity: O(n). As two traversal of the array is needed, so the time complexity is linear.
Auxiliary Space: O(1). As no extra space is required.
METHOD 4 (Using Hashmap):
Approach: This method is somewhat similar to Moore voting algorithm in terms of time complexity, but in this case, there is no need for the second step of Moore voting algorithm. But as usual, here space complexity becomes O(n). In Hashmap(key-value pair), at value, maintain a count for each element(key) and whenever the count is greater than half of the array length, return that key(majority element).
Algorithm:
Create a hashmap to store a key-value pair, i.e. element-frequency pair.
Traverse the array from start to end.
For every element in the array, insert the element in the hashmap if the element does not exist as key, else fetch the value of the key ( array[i] ), and increase the value by 1
If the count is greater than half then print the majority element and break.
If no majority element is found print “No Majority element”
Below is the implementation of above idea:
C++
/* C++ program for finding out majority
element in an array */
#include <bits/stdc++.h>
usingnamespacestd;
voidfindMajority(intarr[], intsize)
{
unordered_map<int, int> m;
for(inti = 0; i < size; i++)
m[arr[i]]++;
intcount = 0;
for(autoi : m)
{
if(i.second > size / 2)
{
count =1;
cout << "Majority found :- "<< i.first<<endl;
break;
}
}
if(count == 0)
cout << "No Majority element"<< endl;
}
// Driver code
intmain()
{
intarr[] = {2, 2, 2, 2, 5, 5, 2, 3, 3};
intn = sizeof(arr) / sizeof(arr[0]);
// Function calling
findMajority(arr, n);
return0;
}
// This code is contributed by codeMan_d
Java
importjava.util.HashMap;
/* Program for finding out majority element in an array */
Time Complexity: O(n). One traversal of the array is needed, so the time complexity is linear.
Auxiliary Space: O(n). Since a hashmap requires linear space.
Thanks, Ashwani Tanwar, Karan Malhotra for suggesting this.
METHOD 5
Approach: The idea is to sort the array. Sorting makes similar elements in the array adjacent, so traverse the array and update the count until the present element is similar to the previous one. If the frequency is more than half the size of the array, print the majority element.
Algorithm:
Sort the array and create a variable count and previous, prev = INT_MIN.
Traverse the element from start to end.
If the current element is equal to the previous element increase the count.
Else set the count to 1.
If the count is greater than half the size of array, print the element as majority element and break.
If no majority element found, print “No majority element”
Time Complexity: O(nlogn). Sorting requires O(n log n) time complexity.
Auxiliary Space: O(1). As no extra space is required.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy