VOOZH about

URL: https://www.geeksforgeeks.org/theory-of-computation/boyer-moore-majority-voting-algorithm/

⇱ Boyer-Moore Majority Voting Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Boyer-Moore Majority Voting Algorithm

Last Updated : 4 Feb, 2026

The Boyer–Moore Voting Algorithm efficiently finds the majority element in an array—an element that appears more than N/2 times—using two passes. In the first pass, it selects a potential candidate by increasing a counter when the same element is encountered and decreasing it when a different element appears, effectively canceling out non-majority elements. In the second pass, the algorithm verifies whether this candidate actually occurs more than N/2 times. This method runs in O(N) time and requires only O(1) extra space, making it both fast and memory-efficient.

Let us see the algorithm and intuition behind its working, by taking an example -

Input :{1,1,1,1,2,3,5}
Output : 1
Explanation : 1 occurs more than 3 times.
Input : {1,2,3}
Output : -1
Explanation: No element appears more than N/2times.

Intuition Behind Working :

The algorithm is based on the idea that if an element occurs more than N/2 times, then all the remaining elements together must occur less than N/2 times.

While traversing the array, we maintain a candidate and a vote count:

  • If the current element matches the candidate, we increment the vote count.
  • If it does not match, we decrement the vote count.
  • When the vote count becomes 0, it means the current candidate cannot be the majority element, so we select a new candidate.

By the end of the first traversal, the remaining candidate is the potential majority element. A second traversal is required to verify whether it actually appears more than N/2 times.

Steps to implement the algorithm :

Step 1: Find a Candidate

Initialize candidate = -1 and votes = 0.

Traverse the array:

  • If votes == 0, set candidate = arr[i] and votes = 1.
  • If arr[i] == candidate, increment votes.
  • Otherwise, decrement votes.

Step 2: Verify the Candidate

  • Count the occurrences of the candidate in the array.
  • If the count is greater than N/2, return the candidate.
  • Otherwise, return -1.

Dry Run for the Given Example

Given array:
arr = {1, 1, 1, 1, 2, 3, 5}

First Traversal (Finding the Candidate)

Element1111235
Votes1234321
Candidate1111111

After the first traversal, the candidate = 1.

Second Traversal (Verifying the Candidate)

Element1111235
Count1234444

Total elements = 7
Majority condition: count > 7 / 2 = 3

Since count = 4 > 3,

1 is the majority element.


Output
 The majority element is : 1

Time Complexity: O(n) ( For two passes over the array )
Space Complexity: O(1)


Comment

Explore