The Majority Element problem is a classic question that tests your understanding of arrays and optimization techniques.
It can be solved efficiently using a clever algorithm called the Boyer-Moore Voting Algorithm.
๐ Problem Statement
Given an array arr[], find the element that appears more than n/2 times.
If no such element exists, return -1.
๐ Examples
Example 1:
Input: [1, 1, 2, 1, 3, 5, 1]
Output: 1
Example 2:
Input: [7]
Output: 7
Example 3:
Input: [2, 13]
Output: -1
๐ง Intuition
If an element appears more than n/2 times:
๐ It will always dominate the array
๐ It cannot be completely canceled out
This idea leads to the Boyer-Moore algorithm.
๐ Approach 1: Brute Force
- Count frequency of each element
- Check if any element appears more than n/2 times
Time Complexity: O(nยฒ)
๐ Approach 2: Hash Map
- Use a dictionary to count frequencies
- Return element with count > n/2
๐ป Code:
```python id="mj1"
def majority_element(arr):
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
n = len(arr)
for num, count in freq.items():
if count > n // 2:
return num
return -1
โก Complexity:
* Time: O(n)
* Space: O(n)
---
๐ Approach 3: Boyer-Moore Voting Algorithm (Optimal)
Step-by-Step:
1. Initialize:
* `candidate = None`
* `count = 0`
2. Traverse the array:
* If `count == 0` โ choose new candidate
* If element == candidate โ increment count
* Else โ decrement count
3. Verify if candidate is actually majority
---
๐ป Python Code
```python id="mj2"
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
return -1
๐งพ Dry Run
For: arr = [1, 1, 2, 1, 3, 5, 1]
- Start โ candidate = 1
- Count increases for matching elements
- Non-matching elements reduce count
- Final candidate = 1
Verify โ appears more than n/2 โ valid
โก Complexity
Time Complexity: O(n)
Space Complexity: O(1)
๐ฅ Why This Works
- Majority element cannot be canceled out
- Uses counting + elimination strategy
- Extremely efficient
โ ๏ธ Edge Cases
- Single element โ return that element
- No majority โ return -1
- All elements same
๐ Conclusion
The Boyer-Moore algorithm is:
โ Optimal
โ Elegant
โ Widely asked in interviews
Top comments (1)
It's easier to write it like this