Majority Element II (Leetcode 229)

Moore's Voting Algorithm

Problem Link: https://leetcode.com/problems/majority-element-ii/

class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        
        count1=0
        count2=0
        # Choose elements to be random values
        ele1=0
        ele2=1
        n=len(nums)
        for i in nums:
            if(i==ele1):
                count1+=1
            elif(i==ele2):
                count2+=1
            elif(count1==0):
                ele1=i
                count1=1
            elif(count2==0):
                ele2=i
                count2=1
            else:
                count1=count1-1
                count2=count2-1
        
        ans=[]
        count1=0
        count2=0
        for i in nums:
            if(i==ele1):
                count1+=1
            if(i==ele2):
                count2+=1
        
        if(count1>n//3):
            ans.append(ele1)
        if(count2>n//3):
            ans.append(ele2)
        
        return ans

Last updated