Algorithms | Major Element In Array
In this article we will talk about finding majority element in array.
Major element is an element that apeears in array more than half of array size times.
If you think about brute force solution, you can get this by doing O(n2) time complexity, meanwhile there are exists linear complexity solution named Moore’s Voting Algorithm.
The basic idea is simple. Setup current major element as first element in array and created variable counter with value 1. Iterate through array and increment counter by one if current value in array equals to current major element, otherwise decrement counter. If counter equals to zero, then current element in array would be a new major element and setup counter to 1.
After end of loop count major element in array, if there are more than half of array size repetitions, that element is major element, otherwise there is no major element.
Algorithm:
1 | package com.company; |