Arrays & Hashing · Pattern 2 of 26
Moore's voting: the majority in O(1) space
Pair off different values and cancel them. Whatever survives is the only possible majority. One pass and two variables, no hash map.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- An element appears more than n / 2 (or n / 3) times
- O(1) extra space is required
The template
int majorityElement(int[] nums) {
int candidate = 0, count = 0;
for (int x : nums) {
if (count == 0) candidate = x; // start a new candidate
count += (x == candidate) ? 1 : -1;
}
return candidate; // verify with a second pass if a majority might not exist
} def majority_element(nums):
candidate, count = 0, 0
for x in nums:
if count == 0:
candidate = x # start a new candidate
count += 1 if x == candidate else -1
return candidate # verify with a second pass if a majority might not exist int majorityElement(vector<int>& nums) {
int candidate = 0, count = 0;
for (int x : nums) {
if (count == 0) candidate = x; // start a new candidate
count += (x == candidate) ? 1 : -1;
}
return candidate; // verify with a second pass if a majority might not exist
} function majorityElement(nums) {
let candidate = 0, count = 0;
for (const x of nums) {
if (count === 0) candidate = x; // start a new candidate
count += x === candidate ? 1 : -1;
}
return candidate; // verify with a second pass if a majority might not exist
} The variations
-
1One candidate: more than n / 2
Every non-majority element can cancel at most one majority element, so the majority always survives.
-
2Two candidates: more than n / 3
At most two values can appear more than n / 3 times. Keep two candidates and two counts, cancel triples, then count both in a second pass.
Mistakes to avoid
- Skipping the verification pass when the problem does not promise a majority.
- For n / 3, checking
count == 0before checking whether x matches a candidate.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.