array and hashmap November 5, 2022

Majority element

Time O(n) Space O(n) Open original problem

We can count all element in the array, and return the element that has the most count.

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        count = collections.defaultdict(int)
        for num in nums:
            count[num] += 1
        return max(count, key=count.get)

Time Complexity: O(n)
Space Complexity: O(n)