Finding the majority element in an array is a common problem in computer science and data analysis. The majority element in an array is the element that appears more than n/2 times, where n is the length of the array. In other words, it’s the element that occurs more frequently than any other element in the array.
Examples:
Input: arr=[2, 2, 3, 4, 2, 2, 5]
Output: 2
Explanation: 2 appears more than n/2 times
Input: arr=[2, 3, 3, 3, 2, 2, 3]
Output: 3
Explanation: 3 appears more than n/2 times
Table of Content
Method 1: Brute Force Approach:
Count the occurrences of each element and check if any element appears more than n/2 times.
Syntax:
for (let i = 0; i < n; i++) {
//implementation
if (count > n / 2) {
return arr[i];
}
}
Example: Below is the implementation of the above approach
function findMajority(arr)
{ const n = arr.length;
for (let i = 0; i < n; i++) {
let count = 0;
for (let j = 0; j < n; j++)
{
if (arr[i] === arr[j]) {
count++;
}
}
if (count > n / 2)
{
return arr[i];
}
}
return null ;
} const arr1 = [2, 2, 3, 4, 2, 2, 5]; console.log(findMajority(arr1)); |
2
Method 2: Sorting Approach:
Sort the array and the majority element will be the middle element (n/2-th element).
Syntax:
arr.sort((a, b) => a - b);
return arr[majorityIndex];
Example: Below is the implementation of the above approach
function findMajority(arr) {
arr.sort((a, b) => a - b);
const majorityIndex =
Math.floor(arr.length / 2);
return arr[majorityIndex];
} const arr2 = [2, 2, 3, 4, 2, 2, 5];
console.log(findMajority(arr2)); |
2
Method 3: Boyer-Moore Voting Algorithm:
This algorithm finds the majority element in linear time and constant space
Syntax:
let candidate = null;
let count = 0;
for (let num of arr) {
if (count === 0) {
candidate = num;
}
count += (num === candidate)
? 1 : -1;
}
return candidate;
Example: Below is the implementation of the above approach
function findMajority(arr) {
let candidate = null ;
let count = 0;
for (let num of arr) {
if (count === 0) {
candidate = num;
}
count += (num === candidate)
? 1 : -1;
}
return candidate;
} const arr3 = [2, 2, 3, 4, 2, 2, 5]; console.log(findMajority(arr3)); |
2