Majority Element
This is a very interesting question I found in CareerCup.com (link):
Given an unsorted array of n numbers, find the number that appears more than n/2 times. Do it in O(n) time and O(1) space.
First, I did not come up with the solution. The solution is described here.
Second, the idea is as follow: If there exists a major element M which appears more than n/2 times, all of the other elements can be paired with this element M. It means that if we crossed out each instance of element M with another element different from M, only instances of M are left.
In short, we need to maintain a counting variable count and a current candidate of major element M:
+ if count == 0 -> assign M to current element
+ else if M == current element -> count++
- else if M != current element -> count –;
After this loop, the candidate of major element is stored in M and it appears at least count time. Please note that M is only the element that seems to appear more than other elements. It does not mean it’s a major element. For example: given 1 2 3 -> M will be 3 which is not a major element.
Therefore, we need to count again all instances of element M to verify the number of occurrence is larger than n/2.
Here is the pseudo code for this algorithm:
FindMajorElement A[1..n]
//init
count = 1
M = A[1];
//find the candidate
for (int i = 2;i <= n;i++)
if (count == 0) M = A[i];
else if (A[i] == M) count++;
else if count--;
count = 0; //reset the variable to number of instance M
//verify
for (int i = 1;i <= n;i++) if (M == A[i]) count++; //return if (count >= n/2) return M
else return null;
That’s it