- What a majority element is — and why there can be at most one
- The Boyer-Moore voting algorithm — O(n) time, O(1) space
- Why the "cancellation" intuition is the key to understanding it
- Why a verification pass is required (and when you can skip it)
- How the algorithm generalizes to finding elements appearing more than n/k times
What a majority element is
In an array of size n, an element is called a majority element if it appears more than ⌊n/2⌋ times — that is, strictly more than half the array. So for [2, 2, 1, 1, 1, 2, 2] (n=7), the majority element is 2 because it appears 4 times (more than 3.5). For [1, 2, 3, 4, 5] (n=5), there's no majority element — no value appears more than 2.5 times.
An important fact: an array can have at most one majority element. If two values each appeared more than n/2 times, their total count would exceed n — impossible. So the question "what is the majority element" has either one answer (the element that appears more than half the time) or none. It can't be ambiguous.
The naive approaches are: (a) sort the array (O(n log n)), then check whether the middle element occurs more than n/2 times — because if a majority exists, it must appear at the middle of the sorted array; or (b) use a hash map to count occurrences (O(n) time, O(n) space). Both are correct, but there's a cleverer way: the Boyer-Moore voting algorithm, which finds the candidate in O(n) time and O(1) space.
Boyer-Moore is one of those rare algorithms that's simultaneously simpler and faster than the obvious approach. The intuition: if you pair up an element of value X with an element of a different value, they "cancel out" — neither is in the majority of the remaining elements. If a majority exists, it can't be fully canceled, because it has more copies than all other elements combined. So you can scan the array once, canceling different-value pairs, and the surviving candidate is the majority (or, if no majority exists, some arbitrary element). Then a second pass verifies whether the candidate is actually the majority.
💡 In one line: use a candidate + counter. For each element, if the counter is 0, set the candidate to that element. Else increment if it matches the candidate, decrement otherwise. After one pass, the candidate is the majority — or a false positive if no majority exists. Verify with a second pass.
Boyer-Moore voting — the O(n) insight
Here's the algorithm:
candidate = arr[0]
count = 0
for each x in arr:
if count == 0:
candidate = x
count = 1
else if x == candidate:
count++
else:
count--
/* verify */
verify_count = 0
for each x in arr:
if x == candidate: verify_count++
if verify_count > n/2:
return candidate
else:
return -1 /* no majority */
Two phases: candidate selection (one pass, tracking a candidate and a count) and verification (one pass, confirming the candidate really is the majority). The candidate-selection phase is the clever part. The verification phase is necessary — because if no majority exists, the algorithm might still produce a non-majority candidate, and we need to catch that.
Trace on [2, 2, 1, 1, 1, 2, 2] (n=7, majority = 2):
| x | candidate | count | Action |
|---|---|---|---|
| 2 | 2 | 1 | count=0 → set candidate, count=1 |
| 2 | 2 | 2 | matches candidate → count++ |
| 1 | 2 | 1 | different → count-- |
| 1 | 2 | 0 | different → count-- |
| 1 | 1 | 1 | count=0 → set candidate, count=1 |
| 2 | 1 | 0 | different → count-- |
| 2 | 2 | 1 | count=0 → set candidate, count=1 |
After one pass, candidate = 2, count = 1. The verification pass counts 4 occurrences of 2, which is more than 7/2 = 3.5 — so 2 is the majority. ✓
Now trace on [1, 2, 3, 4, 5] (n=5, no majority):
- x=1: count=0 → candidate=1, count=1.
- x=2: different → count=0.
- x=3: count=0 → candidate=3, count=1.
- x=4: different → count=0.
- x=5: count=0 → candidate=5, count=1.
Candidate is 5, but the verification pass counts only 1 occurrence — not more than 2.5. So the algorithm correctly reports "no majority." This is why the verification pass is essential.
🎯 Key insight: pairing a majority element with any non-majority element "uses up" one of each. Since the majority has more elements than everything else combined, it can't be fully canceled. The candidate that survives the cancellation is either the true majority or a false positive when no majority exists — hence the need for verification.
Complete C Program
Program: find the majority element (or report none)
#include <stdio.h>
/* Function prototype */
int majorityElement(const int arr[], int n);
int main(void) {
int arr[100];
int n;
printf("How many elements? ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Please enter a valid count between 1 and 100.\n");
return 1;
}
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1) return 1;
}
int result = majorityElement(arr, n);
if (result == -1) {
printf("No majority element found.\n");
} else {
printf("Majority element: %d\n", result);
}
return 0;
}
/* Boyer-Moore majority vote — returns majority or -1 */
int majorityElement(const int arr[], int n) {
int candidate = arr[0];
int count = 0;
/* Phase 1: find candidate */
for (int i = 0; i < n; i++) {
if (count == 0) {
candidate = arr[i];
count = 1;
} else if (arr[i] == candidate) {
count++;
} else {
count--;
}
}
/* Phase 2: verify candidate */
int verify_count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == candidate) verify_count++;
}
if (verify_count > n / 2) return candidate;
return -1;
}
And a simpler counting version — easier to understand, but uses O(range) space and only works for small integer ranges:
Variant: counting via lookup table (simplest)
#include <stdio.h>
#define RANGE 1000
int majorityElementCount(const int arr[], int n) {
int counts[RANGE] = {0};
for (int i = 0; i < n; i++) {
if (arr[i] >= 0 && arr[i] < RANGE) counts[arr[i]]++;
}
for (int i = 0; i < n; i++) {
if (arr[i] >= 0 && arr[i] < RANGE && counts[arr[i]] > n / 2) {
return arr[i];
}
}
return -1;
}
int main(void) {
int arr[] = {2, 2, 1, 1, 1, 2, 2};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Majority: %d\n", majorityElementCount(arr, n));
return 0;
}
This is much simpler — just count each value and check whether any exceeds n/2. But it only works for integer arrays with values in a bounded range, and uses O(RANGE) space. Boyer-Moore works for any type with equality comparison, and uses only O(1) space. Both are valid; pick based on your constraints.
And a version that finds the candidate without verification — valid when the problem guarantees a majority exists:
Variant: candidate only (majority guaranteed)
#include <stdio.h>
int findCandidate(const int arr[], int n) {
int candidate = arr[0], count = 0;
for (int i = 0; i < n; i++) {
if (count == 0) { candidate = arr[i]; count = 1; }
else if (arr[i] == candidate) count++;
else count--;
}
return candidate;
}
int main(void) {
int arr[] = {3, 3, 4, 2, 3, 3, 3};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Candidate: %d\n", findCandidate(arr, n));
return 0;
}
The verification pass is only needed when the problem doesn't guarantee the majority's existence. In LeetCode's "Majority Element" problem, the majority is guaranteed, so you can return the candidate directly. But in general code, always verify — the extra pass is O(n) and cheap, and it prevents returning garbage when there's no majority.
Program Output
A typical run with a majority:
How many elements? 7
Enter 7 integers: 2 2 1 1 1 2 2
Majority element: 2
The element 2 appears 4 times out of 7 — that's more than 3.5, so it's the majority.
A run without a majority:
How many elements? 5
Enter 5 integers: 1 2 3 4 5
No majority element found.
Every element appears exactly once, so none appears more than 2.5 times. The algorithm correctly reports that there's no majority.
With a near-majority (exactly half — not enough):
How many elements? 6
Enter 6 integers: 1 1 1 2 2 2
No majority element found.
Each of 1 and 2 appears 3 times, which is exactly n/2 = 3 — not strictly greater than 3. So neither is a majority. The algorithm correctly refuses to return either. This is an important edge case: "more than n/2" is strict.
With all identical elements:
How many elements? 5
Enter 5 integers: 7 7 7 7 7
Majority element: 7
When every element is the same, that element is trivially the majority. Boyer-Moore handles this cleanly — the candidate is set once and never changes, since all elements match.
With a single element:
How many elements? 1
Enter 1 integers: 42
Majority element: 42
A single element is trivially the majority (appears 1 time, more than 0.5). The candidate phase sets the candidate to arr[0] and never changes it.
With a "false positive" case that verification catches:
How many elements? 5
Enter 5 integers: 1 2 3 1 4
No majority element found.
Trace: candidate starts at 1, count=1. x=2 (different) → count=0. x=3 (count=0) → candidate=3, count=1. x=1 (different) → count=0. x=4 (count=0) → candidate=4, count=1. Candidate is 4, but the array has no 4 — verification catches this and reports no majority. The verification pass is essential; without it, we'd incorrectly return 4.
Step-by-Step Explanation
Let's understand the algorithm deeply, then walk through the code.
1. The cancellation intuition
Imagine pairing elements at random: if two paired elements are different, they cancel; if they're the same, they stay. After all pairs have been formed, the elements that survive are candidates for the majority. If a majority element exists, it must survive, because it has more copies than everything else combined — no combination of pairs can eliminate all its copies.
Boyer-Moore implements this cancellation in a single pass, without ever storing the pairs. The count variable tracks how many unpaired copies of the current candidate we've seen. When we see a non-candidate, it "pairs up" with one copy of the candidate and cancels. When count hits 0, all previous candidates have been canceled — we set a new candidate to the next element. If a majority exists, it will be the final candidate.
2. Why a majority element always survives
Let m be the majority element, and let it appear k > n/2 times. Every non-majority element can pair with at most one copy of m. The total number of non-majority elements is n - k < n/2 < k. So at most n - k copies of m can be canceled. The remaining copies (k - (n - k) = 2k - n > 0) survive. Hence m is the final candidate.
If no majority exists, the survivor is arbitrary — some element whose "net count" happened to stay positive until the end. It might appear many times, but never more than n/2. That's why verification is needed: to confirm the candidate actually crosses the n/2 threshold.
3. Tracing majorityElement([2,2,1,1,1,2,2], 7)
Already traced in the table above. Final candidate = 2, and verification confirms 4 occurrences, which is > 3.5. Return 2. ✓
4. Tracing majorityElement([1,2,3,1,4], 5)
- Start: candidate = 1, count = 0.
- i=0, x=1: count=0 → candidate=1, count=1.
- i=1, x=2: different → count=0.
- i=2, x=3: count=0 → candidate=3, count=1.
- i=3, x=1: different → count=0.
- i=4, x=4: count=0 → candidate=4, count=1.
- Loop ends. Candidate = 4.
- Verify: count of 4 in the array = 1. 1 > 5/2=2.5? No. Return -1.
The candidate (4) doesn't pass verification, so the function correctly reports no majority. Without verification, we'd incorrectly return 4.
5. Complexity
Both phases are O(n): the candidate phase visits each element once, the verification phase visits each element once. Total O(n) time. Space is O(1) — two integers (candidate and count). Compare with a hash map, which is O(n) time but O(n) space. Boyer-Moore is strictly better in space complexity, and competitive in time. That's a rare and elegant combination.
6. Why "more than n/2" and not "at least n/2"
The definition uses strict inequality because if a value appears exactly n/2 times, another value (or set of values) also appears n/2 times total, and neither is dominant. For example, in [1, 1, 2, 2] (n=4), both 1 and 2 appear 2 times each — exactly n/2. Neither is "the majority" in a meaningful sense. The strict definition ensures that at most one element can qualify, and that it can be uniquely identified. If you want to find "at least half" candidates, you'd need a different problem formulation.
7. Generalization to "more than n/k"
Boyer-Moore extends to finding all elements appearing more than n/k times. The generalized version maintains k-1 candidates and k-1 counters. For each element, if it matches a candidate, increment that counter. Else if some counter is 0, adopt the element as that candidate. Else decrement all counters. At the end, the surviving candidates are the only possibilities — then verify each. There can be at most k-1 elements appearing more than n/k times, which is why the algorithm can maintain at most k-1 candidates. This generalization is used in data streaming algorithms (finding frequent items in a stream), where you can't store all data.
8. When to use Boyer-Moore
Use Boyer-Moore when: (a) you need O(1) space, or (b) the array is very large and you want to avoid the memory overhead of a hash map, or (c) the elements are of a type that doesn't hash easily (custom structs, etc.) but does support equality. Use the hash map when: (a) you want a simpler implementation, (b) you also need to find all occurrences (Boyer-Moore only finds the majority), or (c) the array is small enough that O(n) space doesn't matter. Both approaches are valid; the choice depends on your constraints.
9. Application in distributed systems
Boyer-Moore generalizes to distributed settings. If you split the array into chunks and run Boyer-Moore on each chunk, you get a candidate and a count from each chunk. You can then combine these (candidate, count) pairs — adding counts for matching candidates, subtracting for differing ones — to get the global candidate. This makes it suitable for streaming analytics (finding the majority in a data stream split across nodes) and for parallel computations. The generalized version for n/k is used in data mining (frequent itemsets) and network monitoring (heavy hitters).
10. Comparison with other approaches
Several algorithms can find the majority element. Here's a summary:
- Sort then check middle: O(n log n) time, O(1) space (in-place sort). Simplest to explain.
- Hash map count: O(n) time, O(n) space. Simple, but memory-heavy for large arrays.
- Boyer-Moore: O(n) time, O(1) space. Optimal, but trickier to understand.
- Bit-by-bit voting: for integer arrays, you can determine each bit of the majority element by counting bits. O(32n) time, O(1) space. Works but is slower than Boyer-Moore.
Boyer-Moore is the best general-purpose solution — optimal in both time and space. The bit-by-bit approach is interesting but not competitive. The hash map is the easiest to write, but uses more memory.
🔍 Try this: extend the algorithm to find all elements appearing more than n/3 times. Maintain two candidates and two counters. For each element, check if it matches a candidate (increment its counter), else if some counter is 0 (adopt as that candidate), else decrement both counters. At the end, verify each candidate with a count pass. This is the k=3 case of the generalization, and it's a classic interview problem (LeetCode #229).
Frequently Asked Questions
1. Why is the verification pass necessary?
Because Boyer-Moore's candidate phase always produces a candidate — even if no majority exists. The candidate is whatever element happened to survive the cancellation, but it might not actually appear more than n/2 times. Verification counts the actual occurrences and confirms the result. Without it, the function would sometimes return a false positive (a non-majority element). The only exception is if the problem explicitly guarantees a majority exists — then you can skip verification and return the candidate directly.
2. Can there be more than one majority element?
No. If two elements each appeared more than n/2 times, their combined count would exceed n, which is impossible. So at most one element can be the majority. This is why the question "what is the majority element" has either one answer or none — never multiple. This property is what makes the problem tractable: you're looking for a single element, not a set.
3. What's the difference between Boyer-Moore and a hash map count?
Both find the majority element in O(n) time. The difference is space: Boyer-Moore uses O(1) space (two integers), while a hash map uses O(n) space (one entry per distinct value). For a small array, the difference doesn't matter. For a huge array with millions of distinct values, the hash map's memory overhead could be prohibitive — Boyer-Moore avoids this entirely. The tradeoff is that Boyer-Moore is trickier to understand, and it only works for finding the majority, not for finding all occurrences.
4. What does "more than n/2" mean exactly?
It means the count is strictly greater than n/2, where n is the array size. For n=7, the count must be ≥ 4. For n=6, the count must be ≥ 4 (since 3 = n/2 exactly, and we need strictly more). For n=5, the count must be ≥ 3. So the threshold is floor(n/2) + 1 in integers. In C, count > n / 2 (with integer division) gives the right answer because integer division truncates toward 0, and the comparison is strict.
5. Can I find the majority element by sorting?
Yes — sort the array (O(n log n) using qsort), then check whether arr[n/2] appears more than n/2 times. If a majority exists, it must occupy the middle position in the sorted array (because it appears more than n/2 times, it must span the middle). So the middle element is the only candidate. Then verify with a count. This is O(n log n) time, O(1) space (in-place sort). It's simpler than Boyer-Moore but asymptotically slower. For small arrays, the difference is negligible; for large arrays, Boyer-Moore's O(n) is faster.
6. How does this generalize to "more than n/k" times?
Maintain k-1 candidates and k-1 counters. For each element, if it matches a candidate, increment that counter. Else if any counter is 0, adopt the element into that slot with count 1. Else decrement all counters. At the end, verify each candidate by counting occurrences. This finds all elements appearing more than n/k times — at most k-1 such elements can exist. It's used in data streaming (finding heavy hitters) and is a natural generalization of the k=2 case.
💡 Tip: Once this works, try the k=3 version — find all elements appearing more than n/3 times. Then generalize further to k=4, k=5, etc. Each step requires more bookkeeping (more candidates, more counters) but the core cancellation idea is unchanged. Then try implementing the algorithm on a stream of numbers (reading from a file or stdin) — since Boyer-Moore only needs O(1) state, it works on streams of any length without storing the data. That's a powerful property for real-world applications, and one that hash maps can't easily replicate.