Majority element
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A majority element is a value that appears in more than half of a list. A clever pairing idea, where every item cancels a different one, finds it in one pass using almost no memory, which is perfect for huge or never-ending streams of votes and events.
Practical use cases
- Web app: Winning option in a huge live poll. A live poll on a streaming site receives millions of votes. Storing and counting each option takes memory, but a single candidate variable and a counter can track a clear winner as votes arrive. If one option truly has more than half, it is the one left standing.
- Web app: Dominant error in a monitoring dashboard. An error-tracking page reads a stream of error codes and wants to flag a code making up more than half of all errors. The pairing method keeps just one code and a count, so it works at any traffic level without a big table.
- System: Fault tolerance and consensus. In replicated databases, several servers vote on a value and the answer backed by more than half wins, even if a few servers are faulty. Majority voting is how an app keeps working when one server in the group crashes or sends a wrong answer.
The story: The Class Monitor Election
Mrs. Sharma's class had to elect a monitor. Votes were slips of paper with a name. The rule: the winner must have more than half of all the votes, a real majority. Aarav counted slowly with a big tally table, one column per name, and his table was always messy.
Zoya whispered a trick to Mira. "Imagine the votes fight pairs, like a game: each slip for our champion meets a slip for someone else, and the two slips destroy each other. A true majority has more slips than everyone else together, so after all the fighting, it still has slips left."
Mira walked through the pile once. She kept just a champion and a strength number. Same name as the champion? Strength goes up. Different name? Both slips cancel, so strength goes down. If strength hits zero, the next slip becomes the new champion. At the end, the survivor is the only person who could be the majority.
This is the Boyer-Moore voting idea for the majority element. It needs only two variables, no tally table. One honest detail: if no one has a majority, the survivor is just a leftover name, so we count again once to confirm.
How to spot this problem, and where you need it
You need to know whether one value dominates a big or endless stream, and building a counting table for every distinct value uses too much memory or too much time.
Signs you need it
- The problem says appears more than half the time, or more than n divided by 2 times.
- Data arrives as a stream, and storing every value or counting each distinct one is impossible.
- You are using a hash map of counts only to find the single most common item.
Where to use it in a project
- Live polls, ratings and vote-tallying features that must show a leader in real time.
- Monitoring and alerting that watches for one dominant status, error, user agent or source in a stream.
The solution
Keep one candidate and a counter that starts at zero. For each item: if the counter is zero, make this item the candidate. If the item equals the candidate, add one to the counter; otherwise subtract one. At the end the candidate is the only possible majority. If the problem does not guarantee a majority, make a second pass to count the candidate and confirm.
Payoff: Before: a table counting every distinct option for millions of votes. After: two variables and one pass, with constant memory.
Explain it like I am 8
In a big pillow fight, every kid from the biggest team knocks out one kid from another team, and both fall down. If one team has more than half the kids, some of its members must still be standing at the end.
How it works, step by step
- Keep a
candidateand acount, both starting empty/0. - For each item: if
countis 0, make this item the candidate and setcount = 1. - Else if the item equals the candidate,
count++. - Else (different item)
count--: the two cancel. - The final candidate is the only possible majority. Count it in a second pass: if its total is more than half of the list size, it is the answer; otherwise there is none.
The code in four languages
PHP
<?php
// Boyer-Moore voting. Returns the majority element, or null if none exists.
function majority(array $votes) {
$candidate = null;
$count = 0;
foreach ($votes as $v) {
if ($count === 0) {
$candidate = $v; // nobody leading: pick this one
$count = 1;
} elseif ($v === $candidate) {
$count++; // supporter
} else {
$count--; // cancels one supporter
}
}
// Second pass: confirm the survivor really has more than half
$real = 0;
foreach ($votes as $v) {
if ($v === $candidate) $real++;
}
return $real > count($votes) / 2 ? $candidate : null;
}
echo (majority(['Z', 'A', 'Z', 'M', 'Z', 'Z', 'A']) ?? 'none') . PHP_EOL; // Z
echo (majority(['Z', 'A', 'M']) ?? 'none') . PHP_EOL; // noneJavaScript
// Boyer-Moore voting. Returns the majority element, or null if none exists.
function majority(votes) {
let candidate = null;
let count = 0;
for (const v of votes) {
if (count === 0) {
candidate = v; // nobody leading: pick this one
count = 1;
} else if (v === candidate) {
count++; // supporter
} else {
count--; // cancels one supporter
}
}
// Second pass: confirm the survivor really has more than half
let real = 0;
for (const v of votes) {
if (v === candidate) real++;
}
return real > votes.length / 2 ? candidate : null;
}
console.log(majority(['Z', 'A', 'Z', 'M', 'Z', 'Z', 'A']) ?? 'none'); // Z
console.log(majority(['Z', 'A', 'M']) ?? 'none'); // noneJava
public class Main {
// Boyer-Moore voting. Returns the majority element, or null if none exists.
static String majority(String[] votes) {
String candidate = null;
int count = 0;
for (String v : votes) {
if (count == 0) {
candidate = v; // nobody leading: pick this one
count = 1;
} else if (v.equals(candidate)) {
count++; // supporter
} else {
count--; // cancels one supporter
}
}
// Second pass: confirm the survivor really has more than half
int real = 0;
for (String v : votes) {
if (v.equals(candidate)) real++;
}
return real > votes.length / 2.0 ? candidate : null;
}
public static void main(String[] args) {
String a = majority(new String[]{"Z", "A", "Z", "M", "Z", "Z", "A"});
String b = majority(new String[]{"Z", "A", "M"});
System.out.println(a != null ? a : "none"); // Z
System.out.println(b != null ? b : "none"); // none
}
}Go
package main
import "fmt"
// majority uses Boyer-Moore voting. The bool is false if no majority exists.
func majority(votes []string) (string, bool) {
candidate := ""
count := 0
for _, v := range votes {
if count == 0 {
candidate = v // nobody leading: pick this one
count = 1
} else if v == candidate {
count++ // supporter
} else {
count-- // cancels one supporter
}
}
// Second pass: confirm the survivor really has more than half
real := 0
for _, v := range votes {
if v == candidate {
real++
}
}
return candidate, real*2 > len(votes)
}
func main() {
for _, votes := range [][]string{{"Z", "A", "Z", "M", "Z", "Z", "A"}, {"Z", "A", "M"}} {
if winner, ok := majority(votes); ok {
fmt.Println(winner)
} else {
fmt.Println("none")
}
}
// Z
// none
}Time: O(n) · Extra space: O(1). Two passes with just two variables. A tally table (hash map) would also be O(n) time but needs O(n) space.
Watch out for
- Skipping the verification pass. Without a true majority, the survivor is just a leftover name and may be wrong.
- Confusing "majority" (more than half) with "most frequent" (plurality). Z with 3 of 7 might lead without being a majority.
- Not resetting the candidate when
countdrops to 0.
Quick check
- How many votes does a "majority" need?
- At least a third
- More than half
- Just the most votes
- When the next vote differs from the candidate, what happens?
- Count goes down by one
- Candidate changes at once
- Count goes up
- Why do we do a second counting pass?
- To sort the votes
- The survivor may not be a real majority
- To make it O(n²)