Bird
Raised Fist0
DSA Cprogramming

Majority Element Moore's Voting Algorithm in DSA C

Choose your learning style10 modes available
Mental Model
Find the element that appears more than half the time by pairing and canceling different elements.
Analogy: Imagine a room where people form pairs of different opinions and leave, the opinion left at the end is the majority.
Array: [2, 2, 1, 1, 1, 2, 2]
Index:  0  1  2  3  4  5  6
Candidate: ↑ at start (index 0)
Count: 1
Dry Run Walkthrough
Input: array: [2, 2, 1, 1, 1, 2, 2]
Goal: Identify the majority element that appears more than half the time
Step 1: Start with candidate = 2 (first element), count = 1
Candidate=2, Count=1
Why: Initialize candidate and count to start tracking majority
Step 2: Look at next element 2, same as candidate, increment count to 2
Candidate=2, Count=2
Why: Same element increases confidence in candidate
Step 3: Next element 1 differs, decrement count to 1
Candidate=2, Count=1
Why: Different element cancels one occurrence of candidate
Step 4: Next element 1 differs again, decrement count to 0
Candidate=2, Count=0
Why: Count zero means candidate lost balance, need new candidate
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 1 same as candidate, increment count to 2
Candidate=1, Count=2
Why: Same element increases count
Step 7: Next element 2 differs, decrement count to 1
Candidate=1, Count=1
Why: Different element cancels one count
Step 8: Next element 2 differs again, decrement count to 0
Candidate=1, Count=0
Why: Count zero means candidate lost balance again
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
Step 10: No more elements, verify candidate 2 appears more than half times (4 times out of 7)
Count of 2 is 4, which is > 3.5, yes majority
Why: Verification step to confirm majority element
Result:
Majority element is 2
Annotated Code
DSA C
#include <stdio.h>

// Function to find candidate for majority element
int findCandidate(int arr[], int size) {
    int count = 1;
    int candidate = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] == candidate) {
            count++; // same element, increase count
        } else {
            count--; // different element, decrease count
            if (count == 0) {
                candidate = arr[i]; // new candidate
                count = 1; // reset count
            }
        }
    }
    return candidate;
}

// Function to check if candidate is actually majority
int isMajority(int arr[], int size, int candidate) {
    int count = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] == candidate) {
            count++; // count occurrences
        }
    }
    return (count > size / 2);
}

int main() {
    int arr[] = {2, 2, 1, 1, 1, 2, 2};
    int size = sizeof(arr) / sizeof(arr[0]);

    int candidate = findCandidate(arr, size);

    if (isMajority(arr, size, candidate)) {
        printf("Majority element is %d\n", candidate);
    } else {
        printf("No majority element found\n");
    }
    return 0;
}
if (arr[i] == candidate) { count++; } else { count--; if (count == 0) { candidate = arr[i]; count = 1; } }
Adjust count and candidate by pairing different elements to find potential majority
for (int i = 0; i < size; i++) { if (arr[i] == candidate) { count++; } }
Count occurrences of candidate to verify majority
OutputSuccess
Majority element is 2
Complexity Analysis
Time: O(n) because we scan the array twice: once to find candidate, once to verify
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: Naive approach counts each element frequency with extra space O(n) or O(n^2) time; Moore's algorithm is more efficient with O(1) space and O(n) time
Edge Cases
Empty array
No candidate found, function returns first element access may cause error
DSA C
int candidate = arr[0]; // assumes non-empty array
Array with one element
That element is majority by default
DSA C
int candidate = arr[0]; // handles single element correctly
No majority element present
Candidate found but verification fails, prints no majority
DSA C
if (isMajority(arr, size, candidate)) { ... } else { ... }
When to Use This Pattern
When you need to find an element that appears more than half the time efficiently, use Moore's Voting Algorithm because it finds a candidate in one pass and verifies in another with minimal space.
Common Mistakes
Mistake: Not verifying the candidate after finding it, assuming it is always majority
Fix: Always count occurrences of candidate to confirm it appears more than half the time
Summary
Finds the element that appears more than half the time in an array efficiently.
Use when you need to identify a majority element with minimal time and space.
The key insight is pairing different elements cancels them out, leaving the majority candidate.

Practice

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

Solution

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

    It 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 other options

    Sorting, finding smallest, or reversing are unrelated to majority element detection.
  3. Final Answer:

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

    Majority element = element with > n/2 occurrences [OK]
Hint: Majority element appears more than half times [OK]
Common Mistakes:
  • Confusing majority element with most frequent element
  • Thinking it sorts the array
  • Assuming it finds smallest or largest element
2. Which of the following is the correct initialization step in Moore's Voting Algorithm in C?
easy
A. int count = 0, candidate = -1;
B. int count = 1, candidate = 0;
C. int candidate = 0, count = 0;
D. int candidate = -1, count = 1;

Solution

  1. Step 1: Identify correct variable initialization

    Moore's Voting Algorithm starts with count = 0 and candidate = -1 (or any invalid index) to indicate no candidate chosen yet.
  2. Step 2: Check other options

    Other options start count or candidate incorrectly, which can cause logic errors.
  3. Final Answer:

    int count = 0, candidate = -1; -> Option A
  4. Quick Check:

    Start with no candidate and zero count [OK]
Hint: Initialize count=0 and candidate invalid (-1) [OK]
Common Mistakes:
  • Starting count at 1 instead of 0
  • Assigning candidate to 0 prematurely
  • Swapping order of variables
3. What is the output of the following C code snippet using Moore's Voting Algorithm?
int arr[] = {2, 2, 1, 1, 1, 2, 2};
int n = 7;
int count = 0, candidate = -1;
for (int i = 0; i < n; i++) {
  if (count == 0) {
    candidate = arr[i];
  }
  if (arr[i] == candidate) {
    count++;
  } else {
    count--;
  }
}
printf("%d", candidate);
medium
A. 1
B. 0
C. 2
D. No majority element

Solution

  1. Step 1: Trace the candidate and count updates

    Start count=0, candidate=-1
    i=0: count=0, candidate=2, count=1
    i=1: arr[i]=2 == candidate=2, count=2
    i=2: arr[i]=1 != candidate=2, count=1
    i=3: arr[i]=1 != candidate=2, count=0
    i=4: count=0, candidate=1, count=1
    i=5: arr[i]=2 != candidate=1, count=0
    i=6: count=0, candidate=2, count=1
  2. Step 2: Final candidate after loop

    Candidate is 2 after loop ends.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    Majority element found = 2 [OK]
Hint: Track count and candidate changes stepwise [OK]
Common Mistakes:
  • Not resetting candidate when count hits zero
  • Confusing candidate with last element
  • Ignoring count decrement on mismatch
4. Identify the bug in this Moore's Voting Algorithm implementation snippet:
int count = 0, candidate = -1;
for (int i = 0; i < n; i++) {
  if (count == 0) {
    candidate = arr[i];
  }
  if (arr[i] != candidate) {
    count++;
  } else {
    count--;
  }
}
medium
A. Candidate initialized incorrectly
B. Candidate is not updated when count is zero
C. Loop does not run for all elements
D. Count increment and decrement conditions are reversed

Solution

  1. Step 1: Check count update logic

    Correct logic: increment count if element equals candidate, decrement otherwise.
    Given code increments count when arr[i] != candidate, which is wrong.
  2. Step 2: Confirm candidate update and loop correctness

    Candidate updates correctly when count == 0.
    Loop runs correctly for all elements.
    Candidate initialization is valid.
  3. Final Answer:

    Count increment and decrement conditions are reversed -> Option D
  4. Quick Check:

    Increment on match, decrement on mismatch [OK]
Hint: Increment count on match, decrement on mismatch [OK]
Common Mistakes:
  • Swapping increment and decrement conditions
  • Not updating candidate when count is zero
  • Incorrect loop bounds
5. Given an array int arr[] = {3, 3, 4, 2, 4, 4, 2, 4, 4}, how can you verify if the candidate found by Moore's Voting Algorithm is actually a majority element?
hard
A. Count occurrences of candidate and check if it is more than n/2
B. Check if candidate is at the first position of the array
C. Verify if candidate is the maximum element in the array
D. No verification needed; candidate is always majority

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 in array.
    If count > n/2, candidate is majority; else no majority element.
  3. Final Answer:

    Count occurrences of candidate and check if it is more than n/2 -> Option A
  4. Quick Check:

    Verify candidate count > n/2 to confirm majority [OK]
Hint: Always verify candidate count > n/2 after algorithm [OK]
Common Mistakes:
  • Assuming candidate is always majority without check
  • Checking candidate position instead of count
  • Confusing majority with max element
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