The majority element problem is a classic problem in computer science, where you're given an array of integers and asked to find the element that appears more than ⌊n/2⌋ times, where n is the size of the array.
Here are the common approaches to solve this problem, ranked from most efficient to least efficient.
1. The 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. As we iterate through the array, if we see the majority element, we increment the counter. If we see a different element, we decrement the counter. If the counter ever reaches zero, we change the majority element to the current element.
🧠 The Logic
Initialize count = 0 and candidate = None.
Iterate through the array:
If count == 0, set candidate = current_element and count = 1.
If current_element == candidate, increment count.
If current_element != candidate, decrement count.
After the loop, candidate is the majority element.
However, this algorithm assumes that a majority element always exists. To confirm, we need a second pass through the array to count the occurrences of the candidate and ensure it occurs more than ⌊n/2⌋ times.
💻 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)
"""
count = 0
candidate = None
# First pass: Find the candidate for majority element
for num in nums:
if count == 0:
candidate = num
count = 1
elif num == candidate:
count += 1
else:
count -= 1
# Second pass: Confirm the candidate occurs more than n/2 times
count = 0
for num in nums:
if num == candidate:
count += 1
return candidate if count > len(nums) / 2 else None
# Example Usage:
arr1 = [3, 2, 3]
print(f"Array: {arr1}, Majority Element: {majority_element_boyer_moore(arr1)}") # Output: 3
arr2 = [2, 2, 1, 1, 1, 2, 2]
print(f"Array: {arr2}, Majority Element: {majority_element_boyer_moore(arr2)}") # Output: 2
2. Hash Map Approach (O(N))
This approach involves using a hash map to count the occurrences of each element in the array.
🧠 The Logic
Create a hash map counts where the keys are the elements and the values are their counts.
Iterate through the array, incrementing the count for each element in the hash map.
After the loop, iterate through the hash map to find the element with a count greater than ⌊n/2⌋.
💻 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)
"""
counts = {}
n = len(nums)
# Count occurrences of each element
for num in nums:
counts[num] = counts.get(num, 0) + 1
# Find the element with count > n/2
for num, count in counts.items():
if count > n / 2:
return num
return None
# Example Usage:
arr1 = [3, 2, 3]
print(f"Array: {arr1}, Majority Element: {majority_element_hash_map(arr1)}") # Output: 3
arr2 = [2, 2, 1, 1, 1, 2, 2]
print(f"Array: {arr2}, Majority Element: {majority_element_hash_map(arr2)}") # Output: 2
3. Sorting Approach (O(N log N))
This approach involves sorting the array and then finding the middle element, which will be the majority element if it exists.
🧠 The Logic
Sort the array in ascending order.
Find the middle index mid = n / 2.
Check if the element at mid and the next ⌊n/2⌋ elements are the same. If they are, return that element as the majority element.
💻 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)*
"""
nums.sort()
n = len(nums)
mid = n // 2
# Check if the middle element and the next n/2 elements are the same
if nums[mid] == nums[min(mid + n // 2, n - 1)]:
return nums[mid]
return None
# Example Usage:
arr1 = [3, 2, 3]
print(f"Array: {arr1}, Majority Element: {majority_element_sorting(arr1)}") # Output: 3
arr2 = [2, 2, 1, 1, 1, 2, 2]
print(f"Array: {arr2}, Majority Element: {majority_element_sorting(arr2)}") # Output: 2
Summary of Approaches
Method
Time Complexity
Space Complexity
Notes
1. Boyer-Moore Voting
O(N)
O(1)
The fastest and generally preferred solution.
2. Hash Map
O(N)
O(N)
Good if you need to count occurrences of all elements.
3. Sorting
O(N log N)
O(1) or O(N)*
Less efficient due to the sorting step.
(Space complexity for sorting depends on the implementation of the sorting algorithm used by the language.)