The "Majority Element" problem is a classic algorithmic challenge. The goal is to find an element that appears more than ⌊n/2⌋ times in an array of size n.
Here are the most common methods to solve this problem, along with their explanations and code examples.
1. Boyer-Moore Voting Algorithm (Optimal - O(N))
This is the most efficient algorithm for finding the majority element. It works by essentially maintaining a counter for the majority element. The idea is that if there is a majority element, it will "cancel out" other elements, and at the end, the candidate will be the majority element.
🧠 The Logic
Initialize a candidate variable to store the potential majority element and a count variable to keep track of its frequency.
Iterate through the array:
a. If count is 0, set the current element as the new candidate and reset count to 1.
b. If the current element matches the candidate, increment count.
c. If the current element is different from the candidate, decrement count.
At the end of the iteration, the candidate is the majority element.
💻 Python Implementation
python
def majority_element_boyer_moore(nums):
"""
Finds the majority element using the Boyer-Moore Voting Algorithm.
Time complexity: O(N)
Space complexity: O(1)
"""
# Initialize the candidate and count
candidate = None
count = 0
for num in nums:
if count == 0:
# Set the current number as the new candidate
candidate = num
count = 1
elif candidate == num:
# If we see the candidate again, increment the count
count += 1
else:
# If we see a different number, decrement the count
count -= 1
# At this point, 'candidate' is the majority element
# In this problem, it's guaranteed to exist, so we can directly return it
return candidate
# Example Usage:
arr1 = [3, 2, 3]
print(f"Majority Element: {majority_element_boyer_moore(arr1)}") # Output: 3
arr2 = [2, 2, 1, 1, 1, 2, 2]
print(f"Majority Element: {majority_element_boyer_moore(arr2)}") # Output: 2
Why it works:
The Boyer-Moore algorithm works because if an element occurs more than n/2 times, it is guaranteed to be the majority. By "pairing off" different elements, the majority element will be the one left at the end.
Time Complexity: O(N)
Space Complexity: O(1)
2. Hash Map (O(N))
Another straightforward approach is to use a hash map to count the occurrences of each element. The element with a count greater than n/2 is the majority element.
🧠 The Logic
Create a hash map (dictionary) to store the count of each element.
Iterate through the array, incrementing the count for each element in the hash map.
As you iterate, check if any element's count exceeds n/2. If so, return that element.
💻 Python Implementation
python
def majority_element_hash_map(nums):
"""
Finds the majority element using a hash map.
Time complexity: O(N)
Space complexity: O(N)
"""
count_map = {}
n = len(nums)
threshold = n // 2
for num in nums:
# Increment the count of the current number
count_map[num] = count_map.get(num, 0) + 1
# Check if the count exceeds the threshold
if count_map[num] > threshold:
return num
# In this problem, a majority element is guaranteed to exist
# So, we should always return before reaching this point
return None
# Example Usage:
arr1 = [3, 2, 3]
print(f"Majority Element: {majority_element_hash_map(arr1)}") # Output: 3
arr2 = [2, 2, 1, 1, 1, 2, 2]
print(f"Majority Element: {majority_element_hash_map(arr2)}") # Output: 2
Time Complexity: O(N)
Space Complexity: O(N)
3. Sorting (O(N log N))
If the array is sorted, the majority element will be at the index n/2 because it occurs more than n/2 times.
🧠 The Logic
Sort the array.
Return the element at index n/2.
💻 Python Implementation
python
def majority_element_sorting(nums):
"""
Finds the majority element by sorting the array.
Time complexity: O(N log N)
Space complexity: O(1) or O(N) (depends on the sorting algorithm)
"""
nums.sort()
n = len(nums)
# The majority element will be at the middle index
return nums[n // 2]
# Example Usage:
arr1 = [3, 2, 3]
print(f"Majority Element: {majority_element_sorting(arr1)}") # Output: 3
arr2 = [2, 2, 1, 1, 1, 2, 2]
print(f"Majority Element: {majority_element_sorting(arr2)}") # Output: 2
Time Complexity: O(N log N) due to sorting.
Space Complexity: O(1) or O(N) depending on the sorting algorithm.
Summary of Approaches
Method
Time Complexity
Space Complexity
Notes
1. Boyer-Moore Voting
O(N)
O(1)
Most efficient and recommended.
2. Hash Map
O(N)
O(N)
Simple to understand; uses extra space.
3. Sorting
O(N log N)
O(1) or O(N)*
Less efficient due to sorting; modifies the original array.
(Space complexity for sorting depends on the implementation of the sorting algorithm used by the language.)
The Boyer-Moore Voting Algorithm is generally the preferred solution due to its optimal time and space complexity.