
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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++)
#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
- Related Articles
- Majority Element II in C++
- Majority Element in Java
- Majority Element in Python
- Check for Majority Element in a sorted array in C++
- Shortest Majority Substring in C++
- Checking for majority element in a sorted array in JavaScript
- Does this array contain any majority element - JavaScript
- Finding the majority element of an array JavaScript
- Check If a Number Is Majority Element in a Sorted Array in Python
- JavaScript Determine the array having majority element and return TRUE if its in the same array
- Program to list of candidates who have got majority vote in python
- Program to find id of candidate who have hot majority vote in Python
- Previous greater element in C++
- Next Greater Element in C++
- Next Smaller Element in C++

Advertisements