Find all array elements occurring more than âŒŠN / 3 âŒ ‹ times | ''Function to find Majority element in an array ; '' if this element is previously seen,  increment count1. ; '' if this element is previously seen,  increment count2. ; '' if current element is different from  both the previously seen variables, decrement both the counts. ;  ;
def findMajority ( arr , n ) : NEW_LINE INDENT count1 = 0 NEW_LINE DEDENT count2 = 0 NEW_LINE = first = 2147483647 NEW_LINE INDENT second = 2147483647 NEW_LINE flag = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if first == arr [ i ] : NEW_LINE count1 += 1 NEW_LINE elif second == arr [ i ] : NEW_LINE count2 += 1 NEW_LINE elif count1 == 0 : NEW_LINE count1 += 1 NEW_LINE DEDENT first = arr [ i ] NEW_LINE INDENT elif count2 == 0 : NEW_LINE count2 += 1 NEW_LINE second = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT count1 -= 1 NEW_LINE count2 -= 1 NEW_LINE count1 = 0 NEW_LINE count2 = 0 NEW_LINE DEDENT ' gain traverse the array and find the NEW_LINE INDENT actual counts . ''' STRNEWLINE ▁ for ▁ i ▁ in ▁ range ( n ) : STRNEWLINE ▁ if ▁ arr [ i ] ▁ = = ▁ first : STRNEWLINE ▁ count1 ▁ + = ▁ 1 STRNEWLINE ▁ elif ▁ arr [ i ] ▁ = = ▁ second : STRNEWLINE count2 ▁ + = ▁ 1 STRNEWLINE ▁ if ▁ count1 ▁ > ▁ int ( n ▁ / ▁ 3 ) : STRNEWLINE ▁ print ( first , ▁ end ▁ = ▁ " ▁ " ) STRNEWLINE ▁ flag ▁ = ▁ 1 STRNEWLINE ▁ if ▁ count2 ▁ > ▁ int ( n ▁ / ▁ 3 ) : STRNEWLINE print ( second , ▁ end ▁ = ▁ " ▁ " ) STRNEWLINE ▁ flag ▁ = ▁ 1 STRNEWLINE ▁ if ▁ flag ▁ = = ▁ 0 : STRNEWLINE ▁ print ( " No ▁ Majority ▁ Element " ) STRNEWLINE ' Driver ▁ code ▁ ''' NEW_LINE DEDENT arr = [ 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE findMajority ( arr , n ) NEW_LINE