Boyer-Moore Voting Algorithm for Streaming Majority Element
Problem Recap: In a stream of data elements, the majority element is the one that appears more than n/2 times (where n is the total number of elements). We need an algorithm that processes the stream in one pass, using O(1) space (constant memory), and O(n) time overall.
This is perfectly solved by the Boyer-Moore Voting Algorithm (developed in 1981). It cleverly simulates a "voting" process where the majority element "cancels out" minorities.
Key Assumptions
A majority element is guaranteed to exist (appears > n/2 times).
Elements are from a finite domain (e.g., integers), but the algorithm works for any hashable type.
If no majority exists, the algorithm may return a false positive—use a second pass for verification if needed (not possible in pure one-pass streaming).
Algorithm Intuition
Maintain a candidate (potential majority) and a count (its "vote lead").
For each element:
If it matches the candidate, increment the vote.
Otherwise, decrement (minority "cancels" a majority vote).
If votes hit zero, reset candidate to the current element.
The majority will always have enough votes to survive, as it outnumbers all others combined.
Pseudocode (Streaming-Friendly)
python
def find_majority_streaming(stream):
"""
Processes a stream (iterator/generator) one element at a time.
Returns the majority element.
"""
candidate = None
count = 0
for num in stream: # One pass over the stream
if count == 0:
candidate = num
if num == candidate:
count += 1
else:
count -= 1
return candidate # Majority candidate
Pairing Argument: Imagine pairing each non-majority with a majority vote—they cancel. Since majority > n/2, at least one majority remains unpaired, ensuring it's the final candidate.
Invariance: At any prefix, if a majority exists in the full stream, the candidate is either the true majority or will be "evicted" later only if overruled (which can't happen due to > n/2).
Handles ties/deletes perfectly in one pass.
Complexity
Time: O(n) — single pass, constant work per element.
Space: O(1) — only tracks candidate and count.
Streaming Fit: Perfect for unbounded/infinite streams (outputs candidate on-the-fly if needed, but finalize at end).
Optional: Verification (Two-Pass Streaming)
If majority isn't guaranteed:
python
def verify_majority(stream, candidate):
count = 0
total = 0
for num in stream:
total += 1
if num == candidate:
count += 1
return candidate if count > total / 2 else None
But this requires buffering or a second stream pass.
Edge Cases
Single element: Returns it (trivially majority).
Empty stream: Undefined (handle as needed).
All identical: Returns it.
No majority (e.g., [1,2,3]): May return wrong—verify if possible.
This algorithm is elegant, battle-tested (used in LeetCode 169, etc.), and the gold standard for streaming majority. Elementary, my dear user—what's your next puzzle? 🕵️♂️