Majority Element (LeetCode 169): Solution and Explanation
An array of size n contains one value that appears more than half the time. Return that value. The problem guarantees such a value exists.
Watch it run step by step
Try your own input and write the code →Intuition
The first solutions that come to mind are counting and sorting. A hash map of counts finds the value whose count passes n / 2 in O(n) time but O(n) space. Sorting is neat, because the majority value must occupy the middle index after sorting, but it costs O(n log n). The question is whether you can find it in one pass with only a couple of variables.
Here is the observation that makes that possible. Pair up elements that differ and throw each pair away. Each discarded pair contains at most one copy of the majority value, so you remove at least as many other values as majority values. Since the majority makes up more than half the array, it can never be fully cancelled out, and whatever survives at the end must be the majority.
The Boyer-Moore voting algorithm performs that pairing on the fly. Keep a candidate and a count. When the count is 0, adopt the current number as the new candidate. Then a matching number raises the count by one, like a vote for the candidate, and a different number lowers it by one, like a vote against. A count dropping to 0 means everything seen since the candidate was chosen has paired off evenly, so you can forget that prefix and start fresh.
Because the majority value outnumbers all others combined, it is the candidate standing when the scan ends. Note that this only holds when a majority is guaranteed. Without that guarantee, a second pass would be needed to confirm the candidate's count.
Approach: Boyer-Moore voting
- Start with
candidate = Noneandcount = 0. - For each number, if
count == 0, make that number the newcandidate. - If the number equals
candidate, incrementcount, otherwise decrement it. - Continue to the end of the array; the counts let different values cancel each other out.
- Return
candidate, which is guaranteed to be the majority element.
Step-by-step example
nums = [2,2,1,1,1,2,2]
- The first 2 arrives with
count = 0, so the candidate becomes 2 and the count becomes 1. The second 2 raises the count to 2. - The next two 1s lower the count to 1 and then 0.
- The third 1 arrives with
count = 0, so the candidate switches to 1 and the count becomes 1. - The next 2 does not match, so the count drops to 0.
- The last 2 arrives with
count = 0, so the candidate becomes 2 again and the count becomes 1. - The scan ends with candidate 2. It appears 4 times out of 7, which is more than half, so 2 is the answer.
Code: Python, Java, C++
1class Solution:
2 def majorityElement(self, nums: List[int]) -> int:
3 candidate = None
4 count = 0
5
6 for num in nums:
7 if count == 0:
8 candidate = num
9 count += 1 if num == candidate else -1
10
11 return candidate1class Solution {
2 public int majorityElement(int[] nums) {
3 int candidate = 0;
4 int count = 0;
5
6 for (int num : nums) {
7 if (count == 0) {
8 candidate = num;
9 }
10 count += (num == candidate) ? 1 : -1;
11 }
12
13 return candidate;
14 }
15}1class Solution {
2public:
3 int majorityElement(vector<int>& nums) {
4 int candidate = 0;
5 int count = 0;
6
7 for (int num : nums) {
8 if (count == 0) {
9 candidate = num;
10 }
11 count += (num == candidate) ? 1 : -1;
12 }
13
14 return candidate;
15 }
16};Time and space complexity
O(n)
The algorithm makes a single pass over the array and does constant work per element.
O(1)
Only candidate and count are stored, no matter how large the array is.
Other approaches
Hash map counting (time O(n), space O(n))
Count occurrences in a dictionary and return the first value whose count exceeds n / 2. It is the most straightforward and easily adapts to finding counts of every value, but it uses memory proportional to the number of distinct values.
Sort and take the middle (time O(n log n), space O(1))
After sorting, the majority value covers more than half the positions, so it must include index n / 2. Return nums[len(nums) // 2]. It is a one-liner but slower than a single pass.
Common mistakes
- Checking
count == 0after updating the count instead of before. The new candidate must be chosen before the current number votes. - Assuming the final candidate is always a majority when the problem does not guarantee one. In that variant, count the candidate in a second pass.
- Returning the value with the highest final
countfrom some other bookkeeping. The count at the end is not the frequency of the candidate, only its surplus after cancellations. - Using
count > n / 2with integer division in a hash map version and comparing against the wrong bound. The majority must appear strictly more than half the time.
Frequently asked questions
How does the Boyer-Moore voting algorithm work?
It keeps a candidate and a counter. Matching values increment the counter and different values decrement it, and when the counter hits 0 the next value becomes the candidate. Since the majority outnumbers all other values together, it is the candidate left at the end.
Can Majority Element be solved in O(1) space?
Yes. Boyer-Moore voting uses only two variables and a single pass, giving O(n) time and O(1) space.
Why does sorting work for Majority Element?
A value that fills more than half the positions in a sorted array must cover the middle position, whatever its value. So the element at index n / 2 is always the majority.