Given an array, the task is to find if the input array contains a majority element or not. An element is
Examples:
Input : arr[] = {2, 3, 9, 2, 2}
Output : Yes
A majority element 2 is present in arr[]
Input : arr[] = {1, 8, 9, 2, 5}
Output : No
A simple solution is to traverse through the array. For every element, count its occurrences. If the count of occurrence of any element becomes n/2, we return true.
An efficient solution is to use hashing. We count occurrences of all elements. If count becomes n/2 or more return true.
Below is the implementation of the approach.
C++
#include <bits/stdc++.h>
using namespace std;
bool isMajority( int a[], int n)
{
unordered_map< int , int > mp;
for ( int i = 0; i < n; i++)
mp[a[i]]++;
for ( auto x : mp)
if (x.second >= n/2)
return true ;
return false ;
}
int main()
{
int a[] = { 2, 3, 9, 2, 2 };
int n = sizeof (a) / sizeof (a[0]);
if (isMajority(a, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class Gfg
{
static boolean isMajority( int a[], int n)
{
HashMap <Integer,Integer> mp = new
HashMap<Integer,Integer>();
for ( int i = 0 ; i < n; i++)
if (mp.containsKey(a[i]))
mp.put(a[i], mp.get(a[i]) + 1 );
else mp.put(a[i] , 1 );
for (Map.Entry<Integer, Integer> x : mp.entrySet())
if (x.getValue() >= n/ 2 )
return true ;
return false ;
}
public static void main (String[] args)
{
int a[] = { 2 , 3 , 9 , 2 , 2 };
int n = a.length;
if (isMajority(a, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isMajority(a):
mp = {}
for i in a:
if i in mp: mp[i] + = 1
else : mp[i] = 1
for x in mp:
if mp[x] > = len (a) / / 2 :
return True
return False
a = [ 2 , 3 , 9 , 2 , 2 ]
print ( "Yes" if isMajority(a) else "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static Boolean isMajority( int []a, int n)
{
Dictionary< int ,
int > mp = new Dictionary< int ,
int >();
for ( int i = 0; i < n; i++)
{
if (mp.ContainsKey(a[i]))
{
var val = mp[a[i]];
mp.Remove(a[i]);
mp.Add(a[i], val + 1);
}
else
{
mp.Add(a[i], 1);
}
}
foreach (KeyValuePair< int , int > x in mp)
if (x.Value >= n / 2)
return true ;
return false ;
}
public static void Main (String[] args)
{
int []a = { 2, 3, 9, 2, 2 };
int n = a.Length;
if (isMajority(a, n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isMajority(a, n)
{
let mp = new Map();
for (let i = 0; i < n; i++){
if (mp.has(a[i])){
mp.set(a[i], mp.get(a[i]) + 1)
} else {
mp.set(a[i], 1)
}
}
for (let x of mp)
if (x[1] >= n/2)
return true ;
return false ;
}
let a = [ 2, 3, 9, 2, 2 ];
let n = a.length;
if (isMajority(a, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)