DEV Community

Mubashir
Mubashir

Posted on

Majority Element

In this task, I worked on finding the majority element in an array.
A majority element is the element that appears more than n/2 times in the array.

MY APPROACH
I created a function that takes an array and returns the majority element, if it exists

EXAMPLE
arr = [2, 2, 1, 2, 3, 2, 2]
output : 2

LOGIC IMPLEMENTED
To solve this efficiently, I used Moore’s Voting Algorithm.
Instead of counting every element, this algorithm helps find the majority element in one pass.

  1. Keep a candidate and a count
  2. Traverse the array:
  3. If count = 0 → update candidate
  4. If element == candidate → increase count
  5. Else → decrease count
class Solution:
    def majorityElement(self, arr):
        count = 0
        candidate = None
        for num in arr:
            if count == 0:
                candidate = num
            if num == candidate:
                count += 1
            else:
                count -= 1
        if arr.count(candidate) > len(arr) // 2:
            return candidate
        else:
            return -1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)