I am studying the Boyer-Moore Algorithm (from here) and I had a quick question - what is the need of the second pass (which essentially just 'confirms' by finding the frequency of that element). Doesn't the first pass itself guarantee that the element found is the majority one? I considered a few examples and felt that a single pass is enough. Could you kindly provide some examples to counter my feeling?
The code (if required) is as below:
int majorityElement(vector<int>& nums) {
int candidate=0, count=0;
for(auto value: nums) {
//update the candidate if the count == 0
if(count==0)
candidate=value;
//if the value == candidate then increment count
if(value==candidate)
count++;
else
//decrement count
count--;
}
//return candidate
return candidate;
}
Edit: If I understand correctly, the algorithm is only applicable when the frequency of the majority element is indeed greater than (vector size())/2. So, is the second pass really required? Whenever we code, we do some trivial sanity checks (like checking if the input vector is empty), so in this case, why do we have a 'sanity check' as a part of an algorithm? Or is there something more to it?