logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
arrays
Arrays
Boyer-Moore Majority Vote Algorithm
Kadane’s Algorithm
Triple Reverse algorithm aka Reversal Algorithm
graph
Cycle detection
Graph
Topological Sort
Tree Traversal
heap
Binary Heap
Binomial Heap
Heap
linked-list
Cycle Detection
Linked List
Sorting
miscellaneous
Finding the majority element
Rotate array by K steps
numerical-algorithms
Finding If Number is Prime
GCD of two numbers
Performing Exponentiation
Prime Numbers
Randomising Data
partitioning
3. Max Consecutive Ones
Hoare'S Partition Scheme
Lomuto Partition Scheme
queue
Deques
Priority Queue
Queue
search
The Binary Search Master Guide
The Rotated Sorted Array Master Guide
sort
Bubble Sort
Counting Sort
Sorting
Insertion Sort
Merge Sort
Pigeon Hole Sort
Quick Sort
Selection Sort
stack
Monotonic Stack
Monotonic Stack
Stack
Reversing an Array
Stack
Tower of Hanoi
tree
Binary Tree Traversal
Centre of gravity
Diameter of Tree
Shortest Path
Algorithmic Pattern›miscellaneous

Finding the majority element

The Boyer-Moore voting method determines the majority element i.e with more than N/2N/2N/2 occurrences among other elements.

!!! info If there is no majority, the algorithm will not recognise this and will continue to output one of the items. To avoid this we can add a check

# Algorithm

First pass identifies an element as a majority

// we count the votes 
// number of votes will be > 0 only for the majority element
int candidate = -1, votes = 0; 
for (int i = 0; i < nums.length; ++i) { 
	// if votes is 0 then replace the candiate
	if(votes == 0) { 
		candidate = nums[i];
	} 
	
	// if the element is different consider it as vote againts 	
	votes+= (candidate == nums[i]) ? +1 : -1;
} 

Second pass confirms that the element identified in the first pass is indeed a majority

int count = 0;
for (int i = 0; i < nums.length; ++i) { 
	if(candidate == nums[i]) count++;
}
 
if(count < (nums.length &gt;&gt; 1) ) return -1;
 
return candidate; 

# Complexity

  • Time Complexity : O(n)\text{O}(n)O(n)
    • Only 2 iteration are made over the array
  • Space Complexity : O(1)\text{O}(1)O(1)
    • No extra space is needed

# Reference

  • Boyer-Moore majority vote algorithm
PreviousSortingNextRotate array by K steps
CONTENTS
AlgorithmComplexityReference