logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
ArraysBoyer-Moore Majority Vote AlgorithmKadane’s AlgorithmTriple Reverse algorithm aka Reversal Algorithm
Cycle detectionDijkstraDisjoint Set UnionGraphTopological SortTraversal algorithmsTree Traversal
Binary HeapBinomial HeapHeap
Cycle DetectionLinked ListSorting
Finding the majority elementRotate array by K steps
Finding If Number is PrimeGCD of two numbersPerforming ExponentiationPrime NumbersRandomising Data
3. Max Consecutive OnesHoare'S Partition SchemeLomuto Partition Scheme
DequesPriority QueueQueue
The Binary Search Master GuideThe Rotated Sorted Array Master Guide
Bubble SortCounting SortInsertion SortMerge SortPigeon Hole SortQuick SortSelection Sort
Monotonic StackMonotonic StackStackReversing an ArrayStackTower of Hanoi
Binary Tree TraversalCentre of gravityDiameter of TreeShortest Path
Algorithmic Pattern/miscellaneous

Finding the majority element

1 min read
On this pageAlgorithm
AlgorithmComplexityReference

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
←PreviousSortingNext→Rotate array by K steps

On this page

AlgorithmComplexityReference