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
Example 1
Output: 3
Example 2
Output: 2
Explanation: 2 appears 4 times out of 7.
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]
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 candidatecount
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
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
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
- First, set
andcandidate to 0. The startingcount is never used, because the count of 0 makes the first number replace it.candidate - Walk the array with a loop that reads each number into
. Ifx is 0,count becomes the newx .candidate - Still inside the loop, compare
withx : an equal number adds 1 tocandidate , a different one takes 1 away.count - When the loop is done, return
.candidate
The main
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:
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]
Look at the 5 on the fifth line, from [5, 1, 5, 2, 5, 3, 5]
The last line, 3, comes from [1, 1, 2, 2, 3]
The original implementation,
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
andcandidate are stored, twocount values, however long the array is. No map of counts is built.int
When no value is promised to fill more than half, counting with a map is the general tool, as in