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
JavaScript Determine the array having majority element and return TRUE if its in the same array
We are required to write a JavaScript function that takes in an array of numbers with repetitive values and returns the number that appears for more than (n/2) number of times where n is the length of the array. If there is no such element in the array, our function should return false.
This problem is commonly known as finding the "majority element" in an array. A majority element is one that appears more than half the time in the array.
Algorithm Approach
We'll use the Boyer-Moore Voting Algorithm, which works in two phases:
- Phase 1: Find a candidate for majority element
- Phase 2: Verify if the candidate actually appears more than n/2 times
Example
const arr = [12, 5, 67, 12, 4, 12, 4, 12, 6, 12, 12];
const arr1 = [3, 565, 7, 23, 87, 23, 3, 65, 1, 3, 6, 7];
const findMajority = arr => {
let maxChar = -Infinity, maxCount = 1;
// Phase 1: Find possible candidate for majority element
for(let i = 0; i < arr.length; i++){
if(maxChar !== arr[i]){
if(maxCount === 1){
maxChar = arr[i];
} else {
maxCount--;
}
} else {
maxCount++;
}
}
// Phase 2: Verify if candidate is actually majority element
const count = arr.reduce((acc, val) => maxChar === val ? ++acc : acc, 0);
return count > arr.length / 2;
};
console.log(findMajority(arr)); // Array with majority element
console.log(findMajority(arr1)); // Array without majority element
Output
true false
How It Works
Let's trace through the first array [12, 5, 67, 12, 4, 12, 4, 12, 6, 12, 12]:
- Phase 1: The algorithm maintains a candidate and count. When it encounters the same element, count increases. When different, count decreases.
-
Phase 2: Count occurrences of the candidate. Element 12 appears 6 times out of 11, which is > 11/2 = 5.5, so return
true.
Alternative Approach Using Map
const findMajorityWithMap = arr => {
const frequency = new Map();
const threshold = arr.length / 2;
// Count frequencies
for(let num of arr) {
frequency.set(num, (frequency.get(num) || 0) + 1);
if(frequency.get(num) > threshold) {
return true;
}
}
return false;
};
console.log(findMajorityWithMap([1, 1, 1, 2, 3])); // true
console.log(findMajorityWithMap([1, 2, 3, 4, 5])); // false
Output
true false
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Boyer-Moore Algorithm | O(n) | O(1) | Memory-efficient solution |
| Using Map/Object | O(n) | O(n) | Easier to understand |
Conclusion
The Boyer-Moore algorithm efficiently finds majority elements in O(n) time with O(1) space. Use the Map approach for simpler logic or when you need to track all element frequencies.
