Problem
Given a sequence of elements, the task is to find the majority (elements that appear more than half of the total) of the sequence.
Algorithm
The algorithm keeps track of two variables: count
and candidate
.
count
: Initially set to zero. Indicates how many timescandidate
has left until being replaced.candidate
: Possible majority element.
Below is the python code of the Boyer-Moore majority vote algorithm.
Its time complexity is , where is the number of elements. Its space complexity is , as it only needs the space for two local variables.
The algorithm will, however, return one of the elements even when the input sequence has no majority. Thus, one must perform a second pass to verify whether or not the returned element is actually a majority.
References
- Wikimedia Foundation. (2024, January 1). Boyer–Moore majority vote algorithm. Wikipedia. Retrieved January 13, 2024, from https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm