Find the element that appears more than n/2 times in an array (guaranteed to exist for the classic version).
Boyer-Moore voting: keep a candidate and a counter; increment when the current element matches the candidate, decrement otherwise, and pick a new candidate when the counter hits zero. The majority element survives. O(n) time, O(1) space — far better than a frequency map.
public static int majority(int[] a) {
int candidate = a[0], count = 0;
for (int x : a) {
if (count == 0) candidate = x;
count += (x == candidate) ? 1 : -1;
}
return candidate;
}function majority(a) {
let candidate = a[0], count = 0;
for (const x of a) {
if (count === 0) candidate = x;
count += (x === candidate) ? 1 : -1;
}
return candidate;
}def majority(a):
candidate, count = None, 0
for x in a:
if count == 0:
candidate = x
count += 1 if x == candidate else -1
return candidateThe voting idea generalizes to consensus/streaming problems where you cannot afford to store counts for every distinct value.
A candidate uses a HashMap of counts (O(n) space). What is the O(1)-space approach?