Open In App

JavaScript Program to Find the Majority Element that occurs more than N/2 Times

We are given a JavaScript array and we need to find out the majority element in it which occurs more than N/2 times where N is the size of the array.

Example:

Input: arr[] = {3, 5, 8, 5, 4, 5, 7, 5, 5};
Output: 5
Explanation: Here, N = 9 and N/2 = 4, 5 appears 5 times in the array which is more than the value of N/2.
Hence, the output is 5.
Input: arr[] = {3, 4, 3, 8, 3};
Output: 3
Explanation: Here, N = 5 and N/2 = 2, 3 appears 3 times in the array which is more than the value of N/2.
Hence, the output is 3.

The Below methods can be used to find the majority element in an array.



Brute Force Approach

In Brute force method, we will use nested loops to traverse through whole array using outer loop and store the count of elements using inner loop. We will check if the count of any element is more than N/2 and return that element.



Example: The below code will help you implement the brute force approach to find the majority element in JavaScript.




function majorityElement(arr) {
    let n = arr.length;
    for (let i = 0; i < n; i++) {
        let cnt = 0;
        for (let j = 0; j < n; j++) {
            if (arr[j] === arr[i]) {
                cnt++;
            }
        }
        if (cnt > Math.floor(n / 2)) {
            return arr[i];
        }
    }
    return -1;
}
 
let arr =
    [3, 5, 8, 5, 4, 5, 7, 5, 5];
let ans =
    majorityElement(arr);
console.log
    ("The majority element in passed array is: ", ans);

Output
The majority element in passed array is:  5

Time Complexity: O(N^2)

Space Complexity: O(1)

Hashing Method

This is a better approach as it reduces time complexity of the program. In the hashing method, we use hashmap to store the key value pair. The key will stored with its count. The element stored in map having count value greater than N/2 will be returned.

Example: The below code example will explain the use of the hashmap to find the majority element in an array.




function majorityElement(arr) {
    const n = arr.length;
    const mpp = new Map();
    for (let i = 0; i < n; i++) {
        if (mpp.has(arr[i])) {
            mpp.set(arr[i], mpp.get(arr[i]) + 1);
        } else {
            mpp.set(arr[i], 1);
        }
    }
    for (let [key, value] of mpp.entries()) {
        if (value > Math.floor(n / 2)) {
            return key;
        }
    }
    return -1;
}
 
const arr =
    [3, 4, 3, 8, 3];
const ans =
    majorityElement(arr);
console.log
    ("The majority element in passed array is: ", ans);

Output
The majority element in passed array is:  3

Time Complexity: O(N), where N is the size of the array.

Space Complexity: O(N), Because, we are using hashmap which will take N memory space in worst case.


Article Tags :