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.
- Keep a candidate and a count
- Traverse the array:
- If count = 0 → update candidate
- If element == candidate → increase count
- 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
Top comments (0)