Given an array of Numbers, any element of the array will be a majority element if that element appears more than array length's 1/2 times in the array.
For example −
If the length of array is 7,
Then if there's any element in the array that appears for at least 4 number of times, it will be considered a majority. And it’s quite apparent that any particular array can have at most one majority element.
We are required to write a JavaScript function that takes in an array of numbers with repetitive values and returns true if there exists a majority element in the array. If there is no such element in the array, our function should return false.
Example
Following is the code −
const arr = [12, 5, 67, 12, 4, 12, 4, 12, 6, 12, 12];
const isMajority = arr => {
let maxChar = -Infinity, maxCount = 1;
// this loop determines the possible candidates for majorityElement
for(let i = 0; i < arr.length; i++){
if(maxChar !== arr[i]){
if(maxCount === 1){
maxChar = arr[i];
}else{
maxCount--;
};
}else{
maxCount++;
};
};
// this loop actually checks for the candidate to be the majority element
const count = arr.reduce((acc, val) => maxChar===val ? ++acc : acc, 0);
return count > arr.length / 2;
};
console.log(isMajority(arr));Output
This will produce the following output in console −
true