Home
DSA Visualizer
Arrays
Boyer-Moore Voting Algorithm
Boyer-Moore Voting Algorithm
The Boyer-Moore voting algorithm finds the majority element of an array in O(N) time and O(1) space.
CANDIDATE 3 · N 7
VOTE
0
1
2
3
4
5
6
Candidate
3
Count
1
Count is 0, so 3 becomes the new candidate. Everything before this point has cancelled out exactly.
Next
3 matches the candidate → count 2.
Array
Intuition
If a majority element exists (appears > n/2 times), it will "cancel out" all other elements combined. By maintaining a candidate and a counter, we can find it in a single pass.
Concept
- Candidate: The current potential majority element.
- Count: A vote strength.
- Rule: If count is 0, pick new candidate. If match, increment count. If mismatch, decrement count.
How it Works
Algorithm:
- Initialize
candidate = null,count = 0. - For each element
x: - If
count == 0, setcandidate = x,count = 1. - Else if
x == candidate,count++. - Else
count--. - Return
candidate.
Step-by-Step Breakdown
Watch the visualization:
- See how the candidate changes when count hits 0.
- Notice how the count increases/decreases based on matches.
When to Use
- Finding the majority element (guaranteed to exist or need verification).
- Streaming algorithms where you can't store all elements.
When NOT to Use
- When you need exact frequencies of all elements (use Hash Map).
- When no majority element is guaranteed (need a second pass to verify).
How to Identify
"Majority element", "Appears more than n/2 times".
Applying for software engineering roles? Free, no sign-up:
