Leetcode 169: Majority Element

Finding the majority element in an array using a Hash Map frequency table.

The original problem is here.

Hash Map Approach

Algorithm

(Note: There is also an $O(1)$ space solution to this problem known as the Boyer-Moore Voting Algorithm, but using a Hash Map frequency table is a very robust general string/array counting pattern!)

My solution

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        max_num = 0
        max_count = 0
        count = {}
        for num in nums:
            count[num] = count.get(num, 0) + 1
            if count[num] > max_count:
                max_num = num
                max_count = count[num]
        return max_num

Complexity Analysis