Find the majority element in array

Ali Tarhini picture Ali Tarhini · Dec 1, 2010 · Viewed 65.1k times · Source

The majority element is the element that occurs more than half of the size of the array.

How to find the majority element in an array in O(n)?

Example input:

{2,1,2,3,4,2,1,2,2}

Expected output:

2

Answer

Hitesh Gupta picture Hitesh Gupta · Feb 28, 2012
// returns -1 if there is no element that is the majority element, otherwise that element

// funda :: if there is a majority element in an array, say x, then it is okay to discard 
// a part of that array that has no majority element, the remaining array will still have
// x as the majority element

// worst case complexity :  O(n)

int findMajorityElement(int* arr, int size) { 
    int count = 0, i, majorityElement;
    for (i = 0; i < size; i++) {
        if (count == 0)
            majorityElement = arr[i];
        if (arr[i] == majorityElement) 
            count++;
        else
            count--;
    }
    count = 0;
    for (i = 0; i < size; i++)
        if (arr[i] == majorityElement)
            count++;
    if (count > size/2)
        return majorityElement;
    return -1;
}