Introduction

The Boyer-Moore Majority Vote algorithm is designed to find the majority element (an element that appears more than half the time) in linear time and constant space. It works by maintaining a candidate and a counter, adjusting the candidate as it iterates through the array.

In the Boyer-Moore Majority Vote algorithm, two candidates and their counters are used to handle the case where there might be more than one element that appears more than n/3 times in the array. This is particularly useful for problems where you need to find all elements that appear more than a certain fraction of the time, such as n/3.

Two Candidates

Counters

First Pass

Second Pass

Consider the array [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]:

First Pass

Second Pass

        public IList<int> MajorityElement(int[] nums)
        {

            int candidate1 = 0, candidate2 = 0, count1 = 0, count2 = 0;

            foreach (var num in nums)
            {
                if (num == candidate1)
                {
                    count1++;
                }
                else if (num == candidate2)
                {
                    count2++;
                }
                else if (count1 == 0)
                {
                    candidate1 = num;
                    count1 = 1;
                }
                else if (count2 == 0)
                {
                    candidate2 = num;
                    count2 = 1;
                }
                else
                {
                    count1--;
                    count2--;
                }
            }

            count1 = count2 = 0;

            foreach (int num in nums)
            {
                if (candidate1 == num)
                    count1++;
                else if (candidate2 == num)
                    count2++;
            }
            var result = new List<int>();
            if (count1 > nums.Length / 3)
                result.Add(candidate1);
            if (count2 > nums.Length / 3)
                result.Add(candidate2);

            return result;
        }

Below is the Output

Output

This makes the Boyer-Moore algorithm very efficient for finding majority elements in terms of both time and space.