Immediate restart
The candidate changes whenever balance drops to zero. A new candidate is adopted from the very next element — the algorithm restarts seamlessly.
In a noisy crowd, one chant dominates — more than half the voices repeat the same word. Boyer-Moore's voting algorithm finds it in a single scan: maintain a candidate and a counter. Each matching voice increments the count; each dissenting voice decrements it. When the count hits zero, switch candidates. The majority voice always survives the cancellation. O(n) time. O(1) space.
Maintain a candidate and a balance counter. When balance hits zero, adopt the current value as the new candidate. Matching values reinforce (balance++); mismatches cancel (balance−−). The true majority always survives because it can't be fully cancelled.
Boyer–Moore voting: every non-majority element cancels against a majority element. The majority survives because it has more copies than all others combined.
Set candidate = null and balance = 0. No vote has been cast yet.
For each element: if balance == 0, adopt the current value as the new candidate and set balance = 1.
If the current value matches the candidate, increment balance. Otherwise, decrement it — a cancellation.
After the full scan, the candidate is the majority element. It survives because it appears more than ⌊n/2⌋ times.
Understanding boundary behavior is as important as the main algorithm path.
The candidate changes whenever balance drops to zero. A new candidate is adopted from the very next element — the algorithm restarts seamlessly.
An array with one element has a trivial majority. The candidate is set once and never challenged.
Time: O(n) — single pass.
Space: O(1) — two variables.