Moore's Voting Algorithm

Agenda:

  1. What is Moore's Voting Algorithm?
  2. Analogy
  3. Logic
  4. Why it works?
  5. Code

[1] What is Moore's Voting Algorithm?

Moore's Voting Algorithm, also known as the Boyer–Moore majority vote algorithm, is an efficient algorithm for finding the majority element in an array. 

It operates in linear time complexity O(N) and constant space complexity O(1), making it highly efficient for large datasets.

TC: O(N)

SC: O(1)

[2] Analogy

Consider an election scenario where different political parties receive votes from voters. The party with more than 50% of the votes can form the government. 

Similarly, in our array, we aim to identify the element that appears more than half of the time, analogous to the winning political party.

Think of this array as a collection of votes from the voters for different political parties.

Now as we know the party which has >50% votes can form the government.

So, our above question is analogous to this situation.

[3] Logic

In simple and easy terms:

We increment a count variable every time we see the vote from the majority party and decrement it whenever a vote from some other party is occurred, we can guarantee that, count>0.

Detailed Logic:

  1. Initialize a count variable and a majority variable to track the current majority element.
  2. Traverse the array, incrementing the count if the current element matches the majority element and decrementing otherwise.
  3. If the count becomes zero, update the majority element to the current element.
  4. By the end of the traversal, the majority variable holds the majority element.

[4] Why it works?

  • Moore's Voting Algorithm works because the majority element appears more than half of the time in the array. 
  • As we traverse the array, if the count becomes zero, it indicates that the previous majority element's frequency is equal to or less than the sum of the frequencies of the other elements encountered so far. 
  • Therefore, the next element becomes the majority element. Eventually, the final answer will always be the majority element.

[5] Code

Problem: https://leetcode.com/problems/majority-element/

Solution:

class Solution {

public:

    int majorityElement(vector<int>& nums) {

        int majority,count=0;

        for(int i=0;i<nums.size();i++)

        {

            if(count)

            {

                count+=(nums[i]==majority ? 1 : -1);

            }

            else

            {

                majority=nums[i];

                count=1;

            }

        }

        return majority;

    }

};

Comments

Popular posts from this blog

KMP Algorithm: Pattern Searching in Text

Z-Function Algorithm: Substring Search

Back of the envelope estimations