Checking for majority element in a sorted array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Majority Element:

A majority element in an array arr of length l is an element that appears more than l/2 times and hence there is at most one such element.

We need to write a JavaScript function, say isMajority() that takes an array arr which is always sorted in the increasing order as the first argument.

The second argument of the function will be a number, for which we will search the array and return true if that number is the majority element or false otherwise.

For example −

If the input array and the number are −

const arr = [5, 5, 5, 12, 15];
const num = 5;

Then the output should be −

const output = true;

because 5 appears for 3 times which is greater than (5 / 2) = 2.5. (half of the length of the array).

It is given that the array is sorted and if there exists a majority element, it will always be the middle element because that number will have to span over at least more than half of the array.

We can use this logic to check if the given number is the majority element.

Example

The code for this will be −

 Live Demo

const arr = [5, 5, 5, 12, 15];
const num = 5;
const isMajority = (arr = [], num = 1) => {
   const { length } = arr;
   if(!length){
      return false;
   };
   const middle = Math.floor(length / 2);
   if(arr[middle] === num){
      return true;
   }else{
      return false;
   };
};
console.log(isMajority(arr, num));

Output

And the output in the console will be −

true
raja
Published on 27-Feb-2021 10:16:23
Advertisements