Home
DSA Course
Arrays
Boyer-Moore Voting Algorithm
Boyer-Moore Voting Algorithm
Visualize finding the Majority Element in O(N) time and O(1) space.
Candidate
-
Count
0
Ready to find Majority Element.
2
02
11
21
31
42
52
6See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.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".
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
