Boyer-Moore Majority Voting Algorithm
Last Updated :
25 Jul, 2024
The Boyer-Moore voting algorithm is one of the popular optimal algorithms which is used to find the majority element among the given elements that have more than N/ 2 occurrences. This works perfectly fine for finding the majority element which takes 2 traversals over the given elements, which works in O(N) time complexity and O(1) space complexity.
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
This algorithm works on the fact that if an element occurs more than N/2 times, it means that the remaining elements other than this would definitely be less than N/2. So let us check the proceeding of the algorithm.
- First, choose a candidate from the given set of elements if it is the same as the candidate element, increase the votes. Otherwise, decrease the votes if votes become 0, select another new element as the new candidate.
Intuition Behind Working :
When the elements are the same as the candidate element, votes are incremented whereas when some other element is found (not equal to the candidate element), we decreased the count. This actually means that we are decreasing the priority of winning ability of the selected candidate, since we know that if the candidate is in majority it occurs more than N/2 times and the remaining elements are less than N/2. We keep decreasing the votes since we found some different element(s) than the candidate element. When votes become 0, this actually means that there are the equal number of votes for different elements, which should not be the case for the element to be the majority element. So the candidate element cannot be the majority and hence we choose the present element as the candidate and continue the same till all the elements get finished. The final candidate would be our majority element. We check using the 2nd traversal to see whether its count is greater than N/2. If it is true, we consider it as the majority element.
Steps to implement the algorithm :
Step 1 - Find a candidate with the majority -
- Initialize a variable say i ,votes = 0, candidate =-1
- Traverse through the array using for loop
- If votes = 0, choose the candidate = arr[i] , make votes=1.
- else if the current element is the same as the candidate increment votes
- else decrement votes.
Step 2 - Check if the candidate has more than N/2 votes -
- Initialize a variable count =0 and increment count if it is the same as the candidate.
- If the count is >N/2, return the candidate.
- else return -1.
Dry run for the above example:
Given :
arr[]= 1 1 1 1 2 3 5
votes =0 1 2 3 4 3 2 1
candidate = -1 1 1 1 1 1 1 1
candidate = 1 after first traversal
1 1 1 1 2 3 5
count =0 1 2 3 4 4 4 4
candidate = 1
Hence count > 7/2 =3
So 1 is the majority element.
C++
// C++ implementation for the above approach
#include <iostream>
using namespace std;
// Function to find majority element
int findMajority(int arr[], int n)
{
int i, candidate = -1, votes = 0;
// Finding majority candidate
for (i = 0; i < n; i++) {
if (votes == 0) {
candidate = arr[i];
votes = 1;
}
else {
if (arr[i] == candidate)
votes++;
else
votes--;
}
}
int count = 0;
// Checking if majority candidate occurs more than n/2
// times
for (i = 0; i < n; i++) {
if (arr[i] == candidate)
count++;
}
if (count > n / 2)
return candidate;
return -1;
}
int main()
{
int arr[] = { 1, 1, 1, 1, 2, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
int majority = findMajority(arr, n);
cout << " The majority element is : " << majority;
return 0;
}
Java
import java.io.*;
class GFG
{
// Function to find majority element
public static int findMajority(int[] nums)
{
int count = 0, candidate = -1;
// Finding majority candidate
for (int index = 0; index < nums.length; index++) {
if (count == 0) {
candidate = nums[index];
count = 1;
}
else {
if (nums[index] == candidate)
count++;
else
count--;
}
}
// Checking if majority candidate occurs more than
// n/2 times
count = 0;
for (int index = 0; index < nums.length; index++) {
if (nums[index] == candidate)
count++;
}
if (count > (nums.length / 2))
return candidate;
return -1;
// The last for loop and the if statement step can
// be skip if a majority element is confirmed to
// be present in an array just return candidate
// in that case
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 1, 1, 1, 2, 3, 4 };
int majority = findMajority(arr);
System.out.println(" The majority element is : "
+ majority);
}
}
// This code is contributed by Arnav Sharma
Python
# Python implementation for the above approach
# Function to find majority element
def findMajority(arr, n):
candidate = -1
votes = 0
# Finding majority candidate
for i in range (n):
if (votes == 0):
candidate = arr[i]
votes = 1
else:
if (arr[i] == candidate):
votes += 1
else:
votes -= 1
count = 0
# Checking if majority candidate occurs more than n/2
# times
for i in range (n):
if (arr[i] == candidate):
count += 1
if (count > n // 2):
return candidate
else:
return -1
# Driver Code
arr = [ 1, 1, 1, 1, 2, 3, 4 ]
n = len(arr)
majority = findMajority(arr, n)
print(" The majority element is :" ,majority)
# This code is contributed by shivanisinghss2110
C#
using System;
class GFG
{
// Function to find majority element
public static int findMajority(int[] nums)
{
int count = 0, candidate = -1;
// Finding majority candidate
for (int index = 0; index < nums.Length; index++) {
if (count == 0) {
candidate = nums[index];
count = 1;
}
else {
if (nums[index] == candidate)
count++;
else
count--;
}
}
// Checking if majority candidate occurs more than
// n/2 times
count = 0;
for (int index = 0; index < nums.Length; index++) {
if (nums[index] == candidate)
count++;
}
if (count > (nums.Length / 2))
return candidate;
return -1;
// The last for loop and the if statement step can
// be skip if a majority element is confirmed to
// be present in an array just return candidate
// in that case
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 1, 1, 1, 1, 2, 3, 4};
int majority = findMajority(arr);
Console.Write(" The majority element is : "
+ majority);
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// Function to find majority element
function findMajority(nums)
{
var count = 0, candidate = -1;
// Finding majority candidate
for (var index = 0; index < nums.length; index++) {
if (count == 0) {
candidate = nums[index];
count = 1;
}
else {
if (nums[index] == candidate)
count++;
else
count--;
}
}
// Checking if majority candidate occurs more than
// n/2 times
count = 0;
for (var index = 0; index < nums.length; index++) {
if (nums[index] == candidate)
count++;
}
if (count > (nums.length / 2))
return candidate;
return -1;
// The last for loop and the if statement step can
// be skip if a majority element is confirmed to
// be present in an array just return candidate
// in that case
}
// Driver code
var arr = [ 1, 1, 1, 1, 2, 3, 4 ];
var majority = findMajority(arr);
document.write(" The majority element is : "
+ majority);
// This code is contributed by shivanisinghss2110.
</script>
Output The majority element is : 1
Time Complexity: O(n) ( For two passes over the array )
Space Complexity: O(1)
Similar Reads
Boyer Moore Algorithm in Python
Boyer-Moore algorithm is an efficient string search algorithm that is particularly useful for large-scale searches. Unlike some other string search algorithms, the Boyer-Moore does not require preprocessing, making it ideal where the sample is relatively large relative to the data being searched. Wh
3 min read
Boyer-Moore Algorithm for Pattern Searching in C++
The Boyer-Moore algorithm is an efficient string searching algorithm that is used to find occurrences of a pattern within a text. This algorithm preprocesses the pattern and uses this information to skip sections of the text, making it much faster than simpler algorithms like the naive approach. In
6 min read
Boyer-Moore Algorithm for Pattern Searching in C
In this article, we will learn the Boyer-Moore Algorithm, a powerful technique for pattern searching in strings using C programming language. What is the Boyer-Moore Algorithm?The Boyer-Moore Algorithm is a pattern searching algorithm that efficiently finds occurrences of a pattern within a text. It
7 min read
Flajolet Martin Algorithm
The Flajolet-Martin algorithm is also known as probabilistic algorithm which is mainly used to count the number of unique elements in a stream or database . This algorithm was invented by Philippe Flajolet and G. Nigel Martin in 1983 and since then it has been used in various applications such as ,
5 min read
Introduction to Grover's Algorithm
Grover's algorithm is a quantum algorithm that solves the unstructured search problem. In an unstructured search problem, we are given a set of N elements and we want to find a single marked element. A classical computer would need to search through all N elements in order to find the marked element
7 min read
Boyer-Moore Majority Voting Algorithm for Searching elements having more than K Occurrences
The Boyer-Moore Majority Voting Algorithm is a well-known and efficient algorithm used to find the majority element in an array, i.e., an element that appears more than n/2 times. This algorithm, initially designed by Robert S. Boyer and J Strother Moore in 1981, is widely used in various applicatio
9 min read
Boruvka's Algorithm using Python
Boruvka's algorithm is a greedy algorithm for finding the Minimum Spanning Tree (MST) in a connected, weighted, and undirected graph. It was one of the first algorithms for this problem and is named after Otakar Borůvka, who introduced it in 1926. This algorithm works by repeatedly finding the short
11 min read
Disjoint Set Union (Randomized Algorithm)
A Disjoint set union is an algorithm that is used to manage a collection of disjoint sets. A disjoint set is a set in which the elements are not in any other set. Also, known as union-find or merge-find. The disjoint set union algorithm allows you to perform the following operations efficiently: Fin
15+ min read
Bully Algorithm in Distributed System
The Bully Algorithm is a popular method for electing a coordinator in distributed systems. When nodes or processes in a system need a leader to manage tasks or make decisions, this algorithm helps them choose one, even if some nodes fail. The process involves nodes "bullying" each other by checking
9 min read
Barrett Reduction Algorithm (Optimized Variant)
The Barrett Reduction Algorithm computes the remainder of a big integer x divided by another large integer mod. The procedure precomputes mu, the inverse of mod with regard to the next power of 2. All mod calculations utilize this value. Approach: The Barrett Reduction Algorithm approximates x divid
8 min read