Majority Element in C++


Suppose we have an array; we have to check whether given number x is the majority element of that array or not. The array is sorted. 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.

We can count the occurrences of x in the array, and if the number is greater than n/2, the answer will be true, otherwise false.

Example (C++)

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
bool isMajorityElement(int arr[], int n, int x){
   int freq = 0;
   for(int i = 0; i<n; i++){
      if(arr[i] == x )
         freq++;
      if(arr[i] > x)
         break;
   }
   return (freq > n/2);
}
int main() {
   int arr[] = {1, 2, 3, 3, 3, 3, 6};
   int n = sizeof(arr)/sizeof(arr[0]);
   int x = 3;
   if (isMajorityElement(arr, n, x))
      cout << x << " is the majority element of the array";
   else
      cout << x << " is not the majority element of the array";
}

Input

[1, 2, 3, 3, 3, 3, 6]
3

Output

3 is the majority element of the array

Updated on: 28-Apr-2020

867 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements