MAJORITY ELEMENT IN AN ARRAY
Majority Element in an Array – Moore’s Voting Algorithm
Introduction
The majority element in an array is the element that appears more than n/2 times, where n is the size of the array.
This problem can be solved in multiple ways, but the most efficient one is Moore’s Voting Algorithm, which works in linear time and constant space.
Problem Statement
Given an array arr[], find the majority element:
If an element appears more than
n/2times = return itOtherwise = return
-1
Example
Input:
arr = [1, 1, 2, 1, 3, 5, 1]
Output:
1Solution Code
class Solution:
def majorityElement(self, arr):
candidate = None
count = 0
for num in arr:
if count == 0:
candidate = num
count = 1
elif num == candidate:
count += 1
else:
count -= 1
count = 0
for num in arr:
if num == candidate:
count += 1
if count > len(arr) // 2:
return candidate
else:
return -1Approach Used: Moore’s Voting Algorithm
Idea
We try to find a candidate that could be the majority element by canceling out different elements.
How It Works
Step 1: Find Candidate
Traverse the array:
If
count == 0=> pick a new candidateIf same as candidate => increase count
Else => decrease count
This “cancels out” different elements
Step 2: Verify Candidate
Count how many times the candidate appears
Check if it is more than
n/2
Why This Approach Was Chosen
Works in O(n) time
Uses O(1) space
Much better than counting using maps
Alternative Approaches
HashMap / Dictionary
Easy to implement
Uses extra spaceSorting
Majority will be at middle
Time Complexity: O(n log n)
Why Moore’s Algorithm?
Because it is the most optimized solution
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Important Observation
Majority element cancels out all other elements
If it exists, it will always remain as the final candidate
Edge Cases
Single element = always majority
No majority = return -1
All elements same
Conclusion
Moore’s Voting Algorithm is an efficient and elegant solution for finding the majority element. By canceling out non-majority elements, it ensures that the correct candidate emerges, making it one of the best approaches for this problem.
Comments
Post a Comment