Find the Majority Element II

Problem Description

Solution Explanation

Implementation

class Solution:

    def majorityElement(self, nums: List[int]) -> List[int]:

        count = defaultdict(int)

  

        for n in nums:

            count[n] += 1 # increment each occurence by one

  

            if len(count) <= 2: # as long as values < 2 we don't worry

                continue

            new_count = defaultdict(int) # init a new dict to copy into

            for n, c in count.items():

                if c > 1: 
                # if the value of a count is greater than 1 we add to 
                # the new count, other wise we don't since it equals
                # zero, which we don't add

                    new_count[n] = c - 1

            count = new_count

  

        res = []

        for n in count:

            if nums.count(n) > len(nums) // 3: # check if it meets condit

                res.append(n) # appent to output array

        return res