Majority Element | LeetCode 169 | Python | Solution

Click here to see the problem details on LeetCode.

Solution

Simple problem. We need to find out the majority element from an integer array.
Suppose we have an array: [5, 5, 1, 2, 5, 1, 3, 5, 5]. In this array, the number 5 appears five times. And it’s the majority element of the array.

The problem description says that the majority element will appear more than n/2 times, where n is the length of the given array. That means, if we sort it, we will get the majority element at position n/2 from the given array.

So the solution is simple. First, we will sort the array using Python built-in function. Then we will count the total length. If we get the length, we know how to access an element from an array. So, we will access the n/2th element from the sorted array, which is the majority element.

Let’s see the solution in Python.

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        
        sorted_array = sorted(nums)
        n = len(nums)
        
        return sorted_array[n//2]
    
        
        '''
        One Line Solution
        
        return sorted(nums)[len(nums)//2]
        '''

In Python, / gives us the float number as a result. That’s why we have to use //.

I hope you got the idea about the problem and the solution. If you submit this code, it will get accepted.

Scroll to Top