Boyer-Moore's majority vote algorithms can be used to determine the majority element in a linear time and constant space.
The intuition behind finding the majority element is understandable as it has to be greater than the count of other elements in the input sequence if a majority element exists.
However, there is a variation of this algorithm to find the elements occurring more than [n / 3]
where n
is the length of the sequence.
The algorithm goes like this.
- Start with two empty candidate slots and two counters set to 0.
- for each item:
- if it is equal to either candidate, increment the corresponding count
- else if there is an empty slot (i.e. a slot with count 0), put it in that slot and set the count to 1
- else reduce both counters by 1
I can understand there will be at most (n /3) - 1
entries so we keep two containers and their counts.
But I'm not sure why the last reduce both by 1 is pivotal to this algorithm. I would be very helpful if you explain the intuition behind this.
Code of the above algorithm
vector<int> majorityElement(vector<int>& nums) { int cnt1=0, cnt2=0; int a,b; for(int n: nums){ if (cnt1 == 0 || n == a){ cnt1++; a = n; } else if (cnt2 == 0 || n==b){ cnt2++; b = n; } else{ // This part cnt1--; cnt2--; } } cnt1=cnt2=0; for(int n: nums){ if (n==a) cnt1++; else if (n==b) cnt2++; } vector<int> result; if (cnt1 > nums.size()/3) result.push_back(a); if (cnt2 > nums.size()/3) result.push_back(b); return result; }
variation
, check its first word.) $\endgroup$