Boyer-Moore Majority Vote (JavaScript)
Find a strict majority element in linear time and constant space, plus a generalized Misra-Gries pass for multiple frequent values.
Code
// Boyer-Moore majority vote: O(n) time, O(1) space.
export function majorityElement(values) {
if (!Array.isArray(values) || values.length === 0) return null;
let candidate = null;
let balance = 0;
for (const value of values) {
if (balance === 0) {
candidate = value;
balance = 1;
} else if (value === candidate) {
balance += 1;
} else {
balance -= 1;
}
}
let occurrences = 0;
for (const value of values) {
if (value === candidate) occurrences += 1;
}
return occurrences > values.length / 2 ? candidate : null;
}
export function majorityElements(values, threshold = 0.5) {
if (!(threshold > 0 && threshold <= 1)) {
throw new RangeError("threshold must be in (0, 1]");
}
const slots = Math.max(1, Math.ceil(1 / threshold) - 1);
const counters = new Map();
for (const value of values) {
if (counters.has(value)) {
counters.set(value, counters.get(value) + 1);
} else if (counters.size < slots) {
counters.set(value, 1);
} else {
for (const [key, count] of counters) {
if (count === 1) counters.delete(key);
else counters.set(key, count - 1);
}
}
}
const totals = new Map();
for (const value of values) {
if (counters.has(value)) totals.set(value, (totals.get(value) ?? 0) + 1);
}
return [...totals]
.filter(([, count]) => count > values.length * threshold)
.map(([value]) => value);
}How the snippet works
Boyer-Moore Majority Vote (JavaScript) comes down to the functions majorityElement and majorityElements.
for (const value of values) and for (const [key, count] of counters) nest, one inside the other. When the guard condition holds, RangeError is thrown rather than a bogus value returned.
It builds and returns a fresh value rather than reusing its inputs.
Using it
The primary signature is export function majorityElement(values)
Treat majorityElement as the API: import it, and ignore the supporting code.
Key statements
if (counters.has(value)) totals.set(value, (totals.get(value) ?? 0) + 1);
if (!Array.isArray(values) || values.length === 0) return null;
return occurrences > values.length / 2 ? candidate : null;
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does `majorityElement` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- What does the snippet do with malformed data?
- `RangeError` is raised at the guard, so invalid state never reaches the main logic.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `majorityElement`, `majorityElements` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.