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 times candidate has left until being replaced.
  • candidate: Possible majority element.

boyer-moore-majority-vote-visualised

Below is the python code of the Boyer-Moore majority vote algorithm.

def boyer_moore_majority_vote(arr: List[int]) -> int:
    count, candidate = 0, 0
 
    for elem in arr:
        if count == 0:
            candidate = elem
        if candidate == elem:
            count += 1
        else:
            count -= 1
 
    return candidate

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