Majority Element
Easy
Topics
Given an array nums of size n, return the majority element (the one appearing more than n/2 times). It always exists.
Example 1
the majority value
The majority element occupies more than half the cells, so pairing it off against every other value still leaves it standing.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [3,2,3] Output: 3
Example 2
the majority value
Input: nums = [2,2,1,1,1,2,2] Output: 2
Constraints
- n == nums.length
- 1 <= n <= 5*10^4
- The majority element always exists.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Because the majority element occurs more than n/2 times, if we cancel out pairs of different elements, the majority can never be fully cancelled — it will always survive.
Boyer–Moore voting implements this: hold one candidate and a counter; matching votes add, differing votes subtract.
Approach
- Keep
candidateandcount = 0. - When
counthits 0, adopt the current element as the candidate. - If the element equals the candidate, increment count; otherwise decrement.
- The final candidate is the majority (guaranteed to exist).
Walkthrough
nums = [2, 2, 1, 1, 1, 2, 2]
2: cand=2 cnt=1
2: cnt=2
1: cnt=1
1: cnt=0
1: cand=1 cnt=1
2: cnt=0
2: cand=2 cnt=1 -> answer 2Complexity
- Time — O(n): one pass.
- Space — O(1): two variables, versus O(n) for a frequency map.
Common Pitfalls
- Start with
count = 0, not 1. Seeding the count at 1 whilecandidateis alreadynums[0]counts the first element twice, and the vote never swings back:[9,2,2]returns 9 instead of 2. - Boyer-Moore only promises a correct answer when a majority genuinely exists. On input with no element past n/2 it returns whatever survived, so if the guarantee is not given, verify the candidate in a second pass.
Full Solution — all languages
class Solution:
def majorityElement(self, nums):
candidate = nums[0]
count = 0
for v in nums:
if count == 0:
candidate = v
count = 1
elif v == candidate:
count += 1
else:
count -= 1
return candidateimport java.util.*;
class Solution {
public int majorityElement(int[] nums) {
int candidate = nums[0], count = 0;
for (int v : nums) {
if (count == 0) {
candidate = v;
count = 1;
} else if (v == candidate) count++;
else count--;
}
return candidate;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int majorityElement(vector<int>& nums) {
int candidate = nums[0], count = 0;
for (int v : nums) {
if (count == 0) {
candidate = v;
count = 1;
} else if (v == candidate) count++;
else count--;
}
return candidate;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var majorityElement = function(nums) {
let candidate = nums[0], count = 0;
for (const v of nums) {
if (count === 0) {
candidate = v;
count = 1;
} else if (v === candidate) count++;
else count--;
}
return candidate;
};