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
-
Economics & Finance
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
2
How It Works
The algorithm uses a hash map to count occurrences of each element. When any element's count exceeds n/2, it immediately returns that element as the majority element.
Alternative Approach: Boyer-Moore Algorithm
For optimal space complexity, we can use the Boyer-Moore majority vote algorithm:
const findMajorityBoyerMoore = (arr) => {
let candidate = null;
let count = 0;
// Phase 1: Find candidate
for (let num of arr) {
if (count === 0) {
candidate = num;
}
count += (num === candidate) ? 1 : -1;
}
// Phase 2: Verify candidate
let occurrences = 0;
for (let num of arr) {
if (num === candidate) occurrences++;
}
return occurrences > Math.floor(arr.length / 2) ? candidate : false;
};
const arr2 = [3, 3, 4, 2, 4, 4, 2, 4, 4];
console.log(findMajorityBoyerMoore(arr2));
4
Comparison
| Method | Time Complexity | Space Complexity |
|---|---|---|
| Hash Map | O(n) | O(n) |
| Boyer-Moore | O(n) | O(1) |
Conclusion
The hash map approach is straightforward and efficient for finding majority elements. For space-optimal solutions, Boyer-Moore algorithm provides O(1) space complexity while maintaining O(n) time complexity.
Advertisements
