Imagine a ballot box with a million votes. You want to know if any candidate got more than half of them â and you can only look at each ballot once, in any order, without saving them. How much scratch paper do you need?
The surprising answer, proved by Robert Boyer and J Strother Moore in 1981, is exactly two variables: a candidate and a count. Their algorithm streams through the sequence from left to right. Each new element either reinforces the current candidate (count goes up) or cancels one "copy" of it (count goes down). When the count hits zero, the candidate is swapped for the new element and the count resets to one. At the end, whatever candidate is left is the only possible majority winner â if a majority exists at all.
That final caveat matters: the algorithm is a filter, not a verifier. If fewer than half the elements are the same value, the surviving candidate is an artefact of the counting dynamics, not a true majority. A single verification pass over the array (or a second read of the stream) confirms or refutes the result.
The algorithm is provably optimal: any algorithm that identifies the majority element without a separate verification pass must read every element, and no algorithm can solve the problem with fewer than time or with o(1) space while streaming. Boyer-Moore hits both bounds simultaneously.
Comments
Loading comments...