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
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 " ) ; } }