![]() |
VOOZH | about |
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.
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:
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.
Initialize candidate = -1 and votes = 0.
Traverse the array:
votes == 0, set candidate = arr[i] and votes = 1.arr[i] == candidate, increment votes.votes.N/2, return the candidate.-1.Given array:arr = {1, 1, 1, 1, 2, 3, 5}
First Traversal (Finding the Candidate)
| Element | 1 | 1 | 1 | 1 | 2 | 3 | 5 |
|---|---|---|---|---|---|---|---|
| Votes | 1 | 2 | 3 | 4 | 3 | 2 | 1 |
| Candidate | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
After the first traversal, the candidate = 1.
Second Traversal (Verifying the Candidate)
| Element | 1 | 1 | 1 | 1 | 2 | 3 | 5 |
|---|---|---|---|---|---|---|---|
| Count | 1 | 2 | 3 | 4 | 4 | 4 | 4 |
Total elements = 7
Majority condition: count > 7 / 2 = 3
Since count = 4 > 3,
1 is the majority element.
The majority element is : 1
Time Complexity: O(n) ( For two passes over the array )
Space Complexity: O(1)