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
A basic approach would be to check whether each element is the majority element or not. We can use two nested loops where the outer loop iterate over the array, and the inner loop counts the occurrences of each element. If we found an element with a frequency greater than n/2, that's our majority element.
Majority Element in C++One element is said to be the majority element when it appears n/2 times in the array. Suppose an array is like {1, 2, 3, 3, 3, 3, 6}, x = 3, here the answer is true as 3 is the majority element of the array. There are four 3s. The size of the array is 7, so we can see 4 > 7/2.
// 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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With