Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linear Time Voting Algorithm. I don't get it

As I was reading this (Find the most common entry in an array), the Boyer and Moore's Linear Time Voting Algorithm was suggested.

If you follow the link to the site, there is a step by step explanation of how the algorithm works. For the given sequence, AAACCBBCCCBCC it presents the right solution.

When we move the pointer forward over an element e:

  • If the counter is 0, we set the current candidate to e and we set the counter to 1.
  • If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.

When we are done, the current candidate is the majority element, if there is a majority.

If I use this algorithm on a piece of paper with AAACCBB as input, the suggested candidate would become B what is obviously wrong.

As I see it, there are two possibilities

  1. The authors have never tried their algorithm on anything else than AAACCBBCCCBCC, are completely incompetent and should be fired on the spot (doubtfull).
  2. I am clearly missing something, must get banned from Stackoverflow and never be allowed again to touch anything involving logic.

Note: Here is a a C++ implementation of the algorithm from Niek Sanders. I believe he correctly implemented the idea and as such it has the same problem (or doesn't it?).

like image 546
Lieven Keersmaekers Avatar asked Apr 23 '09 09:04

Lieven Keersmaekers


3 Answers

The algorithm only works when the set has a majority -- more than half of the elements being the same. AAACCBB in your example has no such majority. The most frequent letter occurs 3 times, the string length is 7.

like image 170
Rafał Dowgird Avatar answered Oct 06 '22 19:10

Rafał Dowgird


Small but an important addition to the other explanations. Moore's Voting algorithm has 2 parts -

  1. first part of running Moore's Voting algorithm only gives you a candidate for the majority element. Notice the word "candidate" here.

  2. In the second part, we need to iterate over the array once again to determine if this candidate occurs maximum number of times (i.e. greater than size/2 times).

First iteration is to find the candidate & second iteration is to check if this element occurs majority of times in the given array.

So time complexity is: O(n) + O(n) ≈ O(n)

like image 27
Srikar Appalaraju Avatar answered Oct 06 '22 18:10

Srikar Appalaraju


From the first linked SO question:

with the property that more than half of the entries in the array are equal to N

From the Boyer and Moore page:

which element of a sequence is in the majority, provided there is such an element

Both of these algorithms explicitly assume that one element occurs at least N/2 times. (Note in particular that "majority" is not the same as "most common.")

like image 7
j_random_hacker Avatar answered Oct 06 '22 19:10

j_random_hacker