Discover the Boyer-Moore Voting Algorithm, an efficient method to find the majority element in a linear time and constant space solution. This guide includes a step-by-step explanation and JavaScript implementation.
What is Boyer-Moore Voting
Algorithm?
The Boyer-Moore Voting Algorithm is a highly
efficient way to find the majority element in an array in linear time
\(O(n)\) and constant space \(O(1)\).
Boyer-Moore
Voting Algorithm (Simple analogy in my own word)
Imagine you have a notebook where you're tracking everyone's shirt
colour at a party. Each time you see a new colour, you write it down and
give it a count of 1. If you see the same colour again, you increase the
count.
If you see a different colour, you decrease the count. Eventually,
when the count reaches zero, it's like saying, "I've paired off this
colour with other colours enough times, now I'll start fresh." At this
point, you reset the colour to whatever you're seeing now and set the
count to 1 again.
By the time you've gone through the whole crowd, you'll have
eliminated all the "balanced/matched" pairs of colours. The colour left
standing with the positive count is the one that showed up the most—it
is the majority colour.