š Majority Element ā Python (Boyer-Moore Voting Algorithm)
Hi All,
Today I solved an important problem: Finding the Majority Element in an array.
š Problem Statement
Given an array arr[], find the majority element.
š A majority element appears more than n/2 times.
š If no such element exists, return -1.
š Examples
Example 1:
arr = [1, 1, 2, 1, 3, 5, 1]
Output:
1
Example 2:
arr = [7]
Output:
7
Example 3:
arr = [2, 13]
Output:
-1
š” Approach
š¹ Method 1: Brute Force
- Count frequency of each element
- Check if count > n/2
ā Time: O(n²)
š¹ Method 2: HashMap
- Store frequency using dictionary
from collections import Counter
def majority_element(arr):
count = Counter(arr)
n = len(arr)
for key in count:
if count[key] > n // 2:
return key
return -1
š¹ Method 3: Boyer-Moore Voting Algorithm (Optimal)
š Most efficient approach
š§ Key Idea
- Maintain a candidate
- Maintain a count
- Cancel out different elements
š§ Step-by-Step Logic
-
Initialize:
candidate = Nonecount = 0
-
Traverse array:
- If count == 0 ā update candidate
- If same ā increment count
- Else ā decrement count
Verify candidate at the end
š» Python Code (Optimal)
def majority_element(arr):
candidate = None
count = 0
# Step 1: Find candidate
for num in arr:
if count == 0:
candidate = num
if num == candidate:
count += 1
else:
count -= 1
# Step 2: Verify candidate
if arr.count(candidate) > len(arr) // 2:
return candidate
else:
return -1
š Dry Run
For:
arr = [1, 1, 2, 1, 3, 5, 1]
Steps:
- Candidate becomes 1
- Count increases/decreases
- Final candidate = 1
Verification ā appears 4 times (> 3)
š„ļø Sample Output
Input: [1, 1, 2, 1, 3, 5, 1]
Output: 1
Input: [2, 13]
Output: -1
ā” Complexity Analysis
| Method | Time | Space |
|---|---|---|
| Brute Force | O(n²) | O(1) |
| HashMap | O(n) | O(n) |
| Boyer-Moore | O(n) ā | O(1) ā |
š§ Why this is important?
- Advanced algorithm (interview favorite)
- Works in constant space
- Efficient for large datasets
ā Conclusion
This problem helped me understand:
- Frequency counting
- Optimized algorithms
- Boyer-Moore Voting Algorithm
š Must-know for coding interviews!
Top comments (0)