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.

2 variations · 2 problems · 2 with animated walkthroughs

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

Moore's Voting Algorithm
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
}

The variations

  1. 1One candidate: more than n / 2

    Every non-majority element can cancel at most one majority element, so the majority always survives.

  2. 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 == 0 before checking whether x matches a candidate.
Next: Kadane's algorithm: the best subarray ending here →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.