DEV Community

Cover image for LeetCode DSA Series #7: 169. Majority Element
David Babalola
David Babalola

Posted on

LeetCode DSA Series #7: 169. Majority Element

This is my run at day 7 of the challenge (I missed yesterday's submission). The problem today is 169. Majority Element.

Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2βŒ‹ times. You may assume that the majority element always exists in the array.

Here is my solution to the problem:

from collections import Counter
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        counts = Counter(nums)
        majority = len(nums) / 2

        for k, v in counts.items():
            if v > majority:
                return k
Enter fullscreen mode Exit fullscreen mode

Time and space complexity are O(N).

Top comments (0)