Majority Element | Function to find the candidate for Majority ; Function to check if the candidate occurs more than n / 2 times ; Function to print Majority Element ; Find the candidate for Majority ; Print the candidate if it is Majority ; Driver code ; Function call
def findCandidate ( A ) : NEW_LINE INDENT maj_index = 0 NEW_LINE count = 1 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if A [ maj_index ] == A [ i ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if count == 0 : NEW_LINE INDENT maj_index = i NEW_LINE count = 1 NEW_LINE DEDENT DEDENT return A [ maj_index ] NEW_LINE DEDENT def isMajority ( A , cand ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if A [ i ] == cand : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if count > len ( A ) / 2 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def printMajority ( A ) : NEW_LINE INDENT cand = findCandidate ( A ) NEW_LINE if isMajority ( A , cand ) == True : NEW_LINE INDENT print ( cand ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ Majority ▁ Element " ) NEW_LINE DEDENT DEDENT A = [ 1 , 3 , 3 , 1 , 2 ] NEW_LINE printMajority ( A ) NEW_LINE