Home
DSA Visualizer
Arrays
Boyer-Moore Voting Algorithm
Boyer-Moore Voting Algorithm Visualization
The Boyer-Moore voting algorithm finds the majority element of an array in O(N) time and O(1) space. Step through it in the interactive Boyer-Moore Voting Algorithm visualization below.
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 Boyer-Moore Voting Algorithm 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.
Boyer-Moore Voting Algorithm Visualization, Step by Step
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".
Practice it on interview problems
LeetCode problems solved with the Hash Map pattern, each with a step-by-step visualizer:
All Hash Map problemsApplying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
