What is the Boyer-Moore voting algorithm?

Why Interviewers Ask This

Senior Data Structures & Algorithms engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.

Answer

The Boyer-Moore Voting algorithm finds the majority element (appearing more than n/2 times) in O(n) time and O(1) space — better than sorting (O(n log n)) or hash map (O(n) space). Key insight: if we cancel out each occurrence of the majority element with a different element, the majority element still survives. Algorithm: maintain a candidate and a count; initialize both; for each element x: if count == 0, candidate = x, count = 1; else if x == candidate, count++; else count--. After one pass, candidate is the majority element (if one exists). Verification pass (if majority not guaranteed): count occurrences of candidate to confirm it appears > n/2 times. Time: O(n). Space: O(1). Why it works: the majority element appears more than n/2 times. Every cancellation reduces both one majority vote and one non-majority vote — majority votes survive. Variant — N/3 majority (elements appearing more than n/3 times — at most 2 such elements): maintain 2 candidates and 2 counts; use same cancel logic for each; verify both candidates at end. N/k majority: requires k-1 candidates. Applications: (1) Finding majority opinion in voting; (2) Database duplicate detection; (3) Stream processing where memory is limited. One of the most elegant algorithms demonstrating that seemingly hard problems have beautiful O(1)-space solutions.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Data Structures & Algorithms answers easy to follow.