Bird
Raised Fist0
DSA C#programming

Majority Element Moore's Voting Algorithm in DSA C#

Choose your learning style10 modes available
Mental Model
Find the number that appears more than half the time by canceling out different numbers until one candidate remains.
Analogy: Imagine a room where people vote for their favorite color. Every time two people with different colors meet, they leave the room together. The color left at the end is the majority color.
Array: [2, 2, 1, 1, 1, 2, 2]
Candidate: 2 ↑
Count: 1
Dry Run Walkthrough
Input: list: [2, 2, 1, 1, 1, 2, 2]
Goal: Find the majority element that appears more than half the time in the list
Step 1: Start with first element as candidate=2, count=1
Candidate=2, Count=1
Why: Initialize candidate and count to start tracking majority
Step 2: Next element is 2, same as candidate, increment count to 2
Candidate=2, Count=2
Why: Same element increases confidence in candidate
Step 3: Next element is 1, different from candidate, decrement count to 1
Candidate=2, Count=1
Why: Different element cancels one count of candidate
Step 4: Next element is 1, different from candidate, decrement count to 0
Candidate=2, Count=0
Why: Count zero means candidate lost support, pick new candidate next
Step 5: Count is zero, pick new candidate=1, count=1
Candidate=1, Count=1
Why: Reset candidate to current element when count is zero
Step 6: Next element is 1, same as candidate, increment count to 2
Candidate=1, Count=2
Why: Same element increases confidence in candidate
Step 7: Next element is 2, different from candidate, decrement count to 1
Candidate=1, Count=1
Why: Different element cancels one count of candidate
Step 8: Next element is 2, different from candidate, decrement count to 0
Candidate=1, Count=0
Why: Count zero means candidate lost support, pick new candidate next
Step 9: Count is zero, pick new candidate=2, count=1
Candidate=2, Count=1
Why: Reset candidate to current element when count is zero
Result:
Candidate=2 is the majority element
Annotated Code
DSA C#
using System;

class MajorityElementFinder
{
    public static int FindMajorityElement(int[] nums)
    {
        int candidate = 0;
        int count = 0;

        foreach (int num in nums)
        {
            if (count == 0)
            {
                candidate = num; // reset candidate when count is zero
                count = 1;
            }
            else if (num == candidate)
            {
                count++; // same element increases count
            }
            else
            {
                count--; // different element decreases count
            }
        }

        return candidate;
    }

    static void Main()
    {
        int[] nums = { 2, 2, 1, 1, 1, 2, 2 };
        int majority = FindMajorityElement(nums);
        Console.WriteLine(majority);
    }
}
if (count == 0) { candidate = num; // reset candidate when count is zero count = 1; }
Reset candidate to current element when count drops to zero
else if (num == candidate) { count++; // same element increases count }
Increase count when current element matches candidate
else { count--; // different element decreases count }
Decrease count when current element differs from candidate
OutputSuccess
2
Complexity Analysis
Time: O(n) because we scan the list once to find the candidate
Space: O(1) because we use only two variables regardless of input size
vs Alternative: Compared to counting frequencies with a dictionary (O(n) time and O(n) space), Moore's Voting uses constant space and is more efficient
Edge Cases
Array with one element
Returns that element as majority
DSA C#
if (count == 0)
{
    candidate = num; // reset candidate when count is zero
    count = 1;
}
Array where no element appears more than half
Algorithm still returns a candidate but it may not be a true majority
DSA C#
return candidate;
Array with all elements the same
Returns that element as majority immediately
DSA C#
else if (num == candidate)
{
    count++; // same element increases count
}
When to Use This Pattern
When you need to find an element that appears more than half the time in a list, use Moore's Voting Algorithm because it efficiently cancels out pairs of different elements to find the majority.
Common Mistakes
Mistake: Not resetting the candidate when count reaches zero
Fix: Add a condition to reset candidate and count when count is zero
Mistake: Assuming the returned candidate is always a majority without verification
Fix: Verify candidate by counting its occurrences if needed
Summary
Finds the element that appears more than half the time by canceling out different elements.
Use when you want to find a majority element efficiently in linear time and constant space.
The key insight is that pairs of different elements can be ignored, leaving the majority element as the last candidate.

Practice

(1/5)
1. What is the main purpose of Moore's Voting Algorithm in an array of integers?
easy
A. To find the element that appears more than half the time
B. To sort the array in ascending order
C. To find the smallest element in the array
D. To count the total number of unique elements

Solution

  1. Step 1: Understand the problem Moore's Voting Algorithm solves

    The algorithm is designed to find the majority element, which is the element that appears more than half the time in the array.
  2. Step 2: Compare with other options

    Sorting, finding smallest element, or counting unique elements are not the goals of this algorithm.
  3. Final Answer:

    To find the element that appears more than half the time -> Option A
  4. Quick Check:

    Majority element = element with >50% frequency [OK]
Hint: Majority element appears more than half times [OK]
Common Mistakes:
  • Thinking it sorts the array
  • Confusing majority with most frequent element without >50%
  • Assuming it finds smallest or unique counts
2. Which of the following is the correct way to initialize the candidate and count variables in C# for Moore's Voting Algorithm?
easy
A. int candidate = -1; int count = 0;
B. int candidate; int count = 1;
C. int candidate = 0; int count = 0;
D. int candidate = 0; int count = 1;

Solution

  1. Step 1: Understand initialization requirements

    Candidate should start with a default value (like 0) and count should start at 0 before processing the array.
  2. Step 2: Check each option

    int candidate = 0; int count = 0; initializes candidate to 0 and count to 0, which is standard. int candidate; int count = 1; leaves candidate uninitialized. int candidate = -1; int count = 0; uses -1 which may be valid but less common. int candidate = 0; int count = 1; starts count at 1 which is incorrect before any element is processed.
  3. Final Answer:

    int candidate = 0; int count = 0; -> Option C
  4. Quick Check:

    Initialize candidate=0 and count=0 before loop [OK]
Hint: Start count at zero before scanning array [OK]
Common Mistakes:
  • Leaving candidate uninitialized
  • Starting count at 1 before processing
  • Using invalid default candidate values
3. What will be the output of the following C# code snippet using Moore's Voting Algorithm?
int[] nums = {2, 2, 1, 1, 1, 2, 2};
int candidate = 0, count = 0;
foreach (int num in nums) {
  if (count == 0) candidate = num;
  count += (num == candidate) ? 1 : -1;
}
Console.WriteLine(candidate);
medium
A. 1
B. 2
C. 0
D. Error

Solution

  1. Step 1: Trace the candidate and count updates

    Start with candidate=0, count=0. Iterate nums:
    - num=2: count=0, candidate=2, count=1
    - num=2: same candidate, count=2
    - num=1: different, count=1
    - num=1: different, count=0
    - num=1: count=0, candidate=1, count=1
    - num=2: different, count=0
    - num=2: count=0, candidate=2, count=1
  2. Step 2: Final candidate after loop

    The final candidate is 2 after processing all elements.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Final candidate = 2 [OK]
Hint: Track count changes; candidate updates when count hits zero [OK]
Common Mistakes:
  • Not updating candidate when count is zero
  • Confusing candidate with last element
  • Ignoring count increments and decrements
4. Identify the error in the following C# implementation of Moore's Voting Algorithm:
int[] nums = {3, 3, 4, 2, 4, 4, 2, 4, 4};
int candidate = 0, count = 0;
foreach (int num in nums) {
  if (count == 0) candidate = num;
  if (num == candidate) count++;
  else count++;
}
Console.WriteLine(candidate);
medium
A. Count is incremented in both if and else, should decrement in else
B. Candidate is not updated when count is zero
C. Candidate should be initialized to -1
D. The array nums is empty

Solution

  1. Step 1: Analyze count updates in loop

    Count is incremented in both if and else branches, so count never decreases. This breaks the algorithm logic.
  2. Step 2: Correct the else branch

    In Moore's Voting Algorithm, count should decrement when current number is not the candidate.
  3. Final Answer:

    Count is incremented in both if and else, should decrement in else -> Option A
  4. Quick Check:

    Count must decrease when num != candidate [OK]
Hint: Count decreases when element differs from candidate [OK]
Common Mistakes:
  • Incrementing count in else instead of decrementing
  • Not updating candidate when count is zero
  • Assuming candidate initialization causes error
5. Given an array int[] nums = {1, 2, 3, 2, 2, 2, 5, 2, 2}, how can you verify after Moore's Voting Algorithm that the candidate is actually the majority element?
hard
A. Sort the array and pick the middle element
B. Assume candidate is majority without verification
C. Check if candidate is the first element in the array
D. Count the occurrences of candidate in the array and check if it is more than half the array length

Solution

  1. Step 1: Understand Moore's Voting Algorithm limitation

    The algorithm finds a candidate but does not guarantee it is majority if none exists.
  2. Step 2: Verify candidate by counting occurrences

    Count how many times candidate appears and compare with half the array length to confirm majority.
  3. Final Answer:

    Count the occurrences of candidate in the array and check if it is more than half the array length -> Option D
  4. Quick Check:

    Verify candidate count > n/2 after algorithm [OK]
Hint: Always verify candidate count > half array length [OK]
Common Mistakes:
  • Skipping verification step
  • Assuming candidate is always majority
  • Using sorting instead of counting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard