Majority Element

easyArrays & Hashing28 stepsJava · Python · C++

Find the value that appears more than n/2 times. Boyer–Moore voting keeps one candidate and a counter: matching values vote for it, others vote against, and when the counter hits zero a new candidate takes over. The true majority always survives.

▶ Watch the animated trace

Traced input: nums = [2, 2, 1, 1, 1, 2, 2] → 2. Original problem: neetcode.io/problems/majority-element

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

Always one full pass with two variables.

Key idea

Common mistakes

Solution

Java
int majorityElement(int[] nums) {
    int candidate = 0, count = 0;
    for (int i = 0; i < nums.length; i++) {
        if (count == 0) {
            candidate = nums[i];
        }
        count += (nums[i] == candidate) ? 1 : -1;
    }
    return candidate;
}
Python
def majorityElement(nums: List[int]) -> int:
    candidate, count = 0, 0
    for x in nums:
        if count == 0:
            candidate = x
        count += 1 if x == candidate else -1
    return candidate
C++
int majorityElement(vector<int>& nums) {
    int candidate = 0, count = 0;
    for (int x : nums) {
        if (count == 0) {
            candidate = x;
        }
        count += (x == candidate) ? 1 : -1;
    }
    return candidate;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Single element
The first element becomes the candidate and is never challenged.
nums = [5]5
Majority at the end
1 and 2 cancel, then 3 takes over.
nums = [1, 2, 3, 3, 3]3
Negative values
Values are compared, not used as indices.
nums = [-1, -1, 2]-1
No majority exists
The algorithm still returns something. Without the problem's guarantee, count the survivor in a second pass.
nums = [1, 2, 3]3
← Contains DuplicateGroup Anagrams →