A Linear Time Majority Vote Algorithm
I love this algorithm because it's amazing and approachable. I first saw it on a LeetCode discuss ...
For further actions, you may consider blocking this person and/or reporting abuse
The fact that the sequence
A, A, A, B, B, C
output C as the leader is a bit underwhelming.I find the
(n/2 + 1)
majority limitation a little harsh, but indeed it's an elegant solution to a very common problem.People will sometimes get stuck on that point and disregard the algorithm. I love that someone out there posted this as a puzzle which is solvable in linear time BUT has this perfect unique solution.
If you enjoy perfs related algo puzzles, I really liked solving this one: codingame.com/training/medium/stoc...
Overall, codingame is a great website.
This looks neat! Thanks for sharing.
This is awesome!!
Could not help but rewrite it in javascript to help me understand it better. It's not the syntax, but me trying to wrap my head around it. here is what I have:
Looks great! Watch out for
unshift()
which could have an O(n) runtime.ah, good point, updated!
The leader election algorithms, who knew that have computers making seemingly simple decisions in a distributed setting could be so hard and fascinating.
en.wikipedia.org/wiki/Leader_election
Wow! Really fascinating stuff. I’m interested in some of the code behind this.
Took me quite some time to comprehend. Good one though!
But I have a couple genuine questions.
Is this algorithm practically applicable? If we needed to implement a voting system, would we use this algorithm?
And, will this behavior reflect in real life where we have huge number of elements?
The fact that the sequence
A, A, A, B, B, C
output C as the leader is a bit underwhelming.I find the
(n/2 + 1)
majority limitation a little harsh, but indeed it's an elegant solution to a very common problem.It seems pretty rare that you'd have a large data set and know that there is a majority without knowing what that majority is. But if that was the case, then this would be the optimal algorithm.
It was more important when older computers had different restrictions:
Your naive solution needs a bit of updating. You never update the max_votes and as such such will only remain 0. Should be
You’re correct! I must have typoed when I copied it over. Thanks, updated.
Your code is missing an important element:
Otherwise, [A, B, C] => C
Hi Valentin, a majority element cannot be confirmed with one-pass but if there is a majority element (as per the problem statement) it will be found 🔍