Majority Element

Find the value that fills more than half of an array, in one pass and with only two variables.

You are given an array of integers nums with n numbers. Return its majority element: the value that appears more than n / 2 times. The array always has one. Try to find it in a single pass over the array, using only a fixed amount of extra memory.

Example 1
Input: nums = [3, 2, 3]
Output: 3
Example 2
Input: nums = [2, 2, 1, 1, 1, 2, 2]
Output: 2
Explanation: 2 appears 4 times out of 7.
Solution

The Idea

Think of a show of hands. If one choice gets more than half of the hands, it wins, however the other hands are split. The array works the same way: each number is one hand, and the majority element is the value that fills more than half of the positions. In Example 2, the array [2, 2, 1, 1, 1, 2, 2] has seven numbers. The value 2 appears four times and 1 three times, and four is more than half of seven.

The obvious way to find the winner is to count every value and pick the biggest count. That works, but it needs a table with one count for each different value. Could we find the winner while remembering only one value and one number?

Here is a thought that helps. Take two numbers with different values out of the array, say one 2 and one 1, and keep doing that. Each time, the majority loses at most one copy, and the other values lose at least one. The majority started with more copies than all the other values together, so it stays ahead after every removal. When no two different values are left, the numbers that remain are all copies of the majority.

The cancelling can happen during a single walk from left to right. Keep one candidate, a value that might be the majority, and a count of its copies not yet cancelled. A number equal to the candidate adds 1 to the count. A different number cancels one copy, so the count goes down by 1. When the count is 0, nothing is waiting, and the next number becomes the new candidate. Look at the picture below.

One pass over 2, 2, 1, 1, 1, 2, 2. The first 2 is the first candidate and the count rises to 2, then falls to 0 after two 1s. The fifth value, 1, becomes a new candidate with count 1, the sixth value, 2, brings the count back to 0, and the last 2 becomes the new candidate with count 1.

The top row is Example 2, and below each number are the candidate and the count after that number is read. The first 2 becomes the first candidate, with count 1, and the second 2 raises the count to 2. The two 1s that follow each cancel one 2, so after the fourth number the count is 0.

The fifth number, a 1, finds nothing waiting and becomes the new candidate, with count 1. The sixth number, a 2, cancels it, and the count is 0 again. The last 2 becomes the new candidate, and the walk ends with candidate 2: the answer.

This way of finding the majority is called the Boyer-Moore voting algorithm, after Robert Boyer and J Strother Moore, who described it.

Solution Approach

Turning that idea into code means settling three things: why the simpler ways fall short, how the candidate and the count change, and what happens when an array has no majority.

Counting and sorting

Why not just count? A HashMap from each value to its number of copies finds the majority in one pass. But the map holds one entry for each different value, so its memory grows with the array.

Sorting is another simple way. The majority fills more than half of the positions, so after sorting its copies always cover the middle position, n / 2. Example 2 sorted reads 1, 1, 1, 2, 2, 2, 2, and position 3, counting from 0, holds a 2. Sorting needs no map, but it takes O(n log n) time, more than one pass.

Keeping the candidate and the count

What should happen to the first number, or to any number that arrives when the count is 0? It becomes the candidate first, and then it is compared with itself, so it adds 1 and the count starts at 1. Every later number either adds 1 or takes 1 away.

Is it safe to forget everything when the count drops to 0? At that moment, the numbers read so far have all been cancelled in pairs of different values. As we saw earlier, removing such pairs keeps the majority ahead in what is left. So the rest of the array still has the same majority, and the walk can start fresh from there.

Arrays without a majority

What if the array has no value that fills more than half? The problem promises it does, and the method relies on that promise. Without it, the walk still ends with some candidate, which may not be a majority at all. In that case, an optional second pass can count the copies of the candidate and check that there are more than n / 2.

Java Solution

The method majorityElement works in these steps:

  1. First, set candidate and count to 0. The starting candidate is never used, because the count of 0 makes the first number replace it.
  2. Walk the array with a loop that reads each number into x. If count is 0, x becomes the new candidate.
  3. Still inside the loop, compare x with candidate: an equal number adds 1 to count, a different one takes 1 away.
  4. When the loop is done, return candidate.

The main method runs both examples, a single number, negative numbers, an array whose count drops to 0 three times, and an array with no majority at all.

Java
public class MajorityElement {

    // Boyer-Moore voting: different values cancel in pairs, the majority survives
    public static int majorityElement(int[] nums) {
        int candidate = 0;
        int count = 0;
        for (int x : nums) {
            if (count == 0) {
                candidate = x;                // everything so far cancelled out
            }
            count += (x == candidate) ? 1 : -1;
        }
        return candidate;
    }

    public static void main(String[] args) {
        System.out.println(majorityElement(new int[] {3, 2, 3}));
        System.out.println(majorityElement(new int[] {2, 2, 1, 1, 1, 2, 2}));
        System.out.println(majorityElement(new int[] {7}));
        System.out.println(majorityElement(new int[] {-5, -5, 7}));
        System.out.println(majorityElement(new int[] {5, 1, 5, 2, 5, 3, 5}));
        System.out.println(majorityElement(new int[] {1, 1, 2, 2, 3}));
    }
}

Running it prints:

Output
3
2
7
-5
5
3

The 3 and the 2 at the top match the answers of Example 1 and Example 2. The 7 comes from [7]: the only number becomes the candidate and nothing cancels it. The -5 shows that negative numbers need no special care, since the method only checks whether two numbers are equal.

Look at the 5 on the fifth line, from [5, 1, 5, 2, 5, 3, 5]. Each 5 is cancelled by the different number after it, so the count drops to 0 three times. Yet every time, the next number is a 5 again, and the last 5 is left as the candidate.

The last line, 3, comes from [1, 1, 2, 2, 3], which has no majority. The 1s and the 2s cancel each other, and the 3 arrives when the count is 0, so it becomes the candidate. The method returns it, even though 3 appears only once out of five. This is the case where the second pass from the Solution Approach is needed.

The original implementation, MajorityElement.java, is on GitHub.

Complexity

The method reads the array once and keeps only two numbers while doing so.

  • Time: O(n), because the loop visits each of the n numbers once and does one comparison and one addition for it. There is no sort and no second pass.
  • Space: O(1). Only candidate and count are stored, two int values, however long the array is. No map of counts is built.

When no value is promised to fill more than half, counting with a map is the general tool, as in Top K Frequent Elements.