Majority Element II: Boyer-Moore Voting Algorithm
Priyanshu Kumar
Backend engineer specializing in Django, REST APIs, and scalable web applications.
Problem Explanation:
In this problem, you're given an array of integers where each number represents a vote for a candidate. The goal is to find all the candidates that have received more than one-third of the total votes. If no such candidate exists, return an empty list. The result should be returned in ascending order.Example 1:
Example 2:
Solution Approach:
To solve this problem efficiently, we can use theBoyer-Moore Voting Algorithm, which is designed to find majority elements in linear time with constant space. The algorithm works in two phases:
领英推荐
Edge Cases:
Code Implementation:
class Solution:
def findMajority(self, arr):
if not arr:
return []
# Initialize variables for two potential majority elements
elm1, elm2 = None, None
count1, count2 = 0, 0
# First pass: Find potential candidates for majority elements
for num in arr:
if num == elm1:
count1 += 1
elif num == elm2:
count2 += 1
elif count1 == 0:
elm1 = num
count1 = 1
elif count2 == 0:
elm2 = num
count2 = 1
else:
count1 -= 1
count2 -= 1
# Second pass: Verify if they are actually majority elements
count1, count2 = 0, 0
for num in arr:
if num == elm1:
count1 += 1
elif num == elm2:
count2 += 1
# Check if they appear more than n/3 times and return result in sorted order
result = []
if count1 > len(arr) / 3:
result.append(elm1)
if count2 > len(arr) / 3:
result.append(elm2)
result.sort() # Ensure ascending order as required by problem statement
return result
# Example usage:
# arr = [2, 1, 5, 5, 5, 5, 6, 6, 6, 6]
# sol = Solution()
# print(sol.findMajority(arr)) # Output: [5, 6]
Time and Space Complexity:
Conclusion:
The Boyer-Moore Voting Algorithm provides an efficient solution to finding elements that appear more than n/3 times in an array. With linear time complexity and constant space usage, this approach is optimal for large datasets where brute-force methods would be too slow or memory-intensive.