Problem - You have to find a majority element in an array . An element is majority element if it occurs more than half times the size of array.
Solution -
- Take two variables ,major which will contain majority element at the end and another count variable.
- Initialize major to first element of the array and set count to one.
- Now traverse the rest of array from the 2nd element.
- For each array element a[i] ,
if ( major==a[i] ) count++; else if ( count == 0 ) { major=a[i]; count=1; } else count--; - At the end of traversing the array, major will consist of majority element.
Example:
A A A C C B B C C C B C C
- initially, major=A , count =1; Now traverse the rest of the array
- major=A , count=2
- major=A , count=3
- major=A , count=2
- major=A , count=1
- major=A , count=0
- major=B , count=1
- major=B , count=0
- major=C , count=1
- major=C , count=2
- major=C , count=1
- major=C , count=2
- major=C , count=3finally majority element = C
Very nice example..