Check if an array has a majority element | Hashing based C ++ program to find if there is a majority element in input array . ; Returns true if there is a majority element in a [ ] ; Insert all elements in a hash table ; Check if frequency of any element is n / 2 or more . ; Driver code
#include <bits/stdc++.h> NEW_LINE 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 ; }