Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Finding the majority element of an array JavaScript
We are given an array of size n, and we are required to find the majority element. The majority element is the element that appears more than [ n/2 ] times.
Example
const arr = [2, 4, 2, 2, 2, 4, 6, 2, 5, 2];
const majorityElement = (arr = []) => {
const threshold = Math.floor(arr.length / 2);
const map = {};
for (let i = 0; i < arr.length; i++) {
const value = arr[i];
map[value] = map[value] + 1 || 1;
if (map[value] > threshold)
return value
};
return false;
};
console.log(majorityElement(arr));
Output
And the output in the console will be −
2
Advertisements
