The Boyer-Moore Majority Vote Algorithm is an algorithm that finds the majority of a sequence of numbers , if the majority exists, in time and space.

Tip

This problem can also be solved by Quickselect in time and space.

Algorithm

  1. Arbitrarily remove two distinct elements, until all the remaining elements have the same value.

Lemma

The value of the remaining elements is the majority of .

  1. Apply the lemma to find the majority.

This algorithm solves the problem in time and space.

int boyer_moore_majority_vote(int n, const std::vector<int> &a) {
	int x = 0, c = 0;
	for (int i = 0; i < n; i++) {
		if (c) {
			c += x == a[i] ? 1 : -1;
		} else {
			x = a[i], c = 1;
		}
	}
	return x;
}