Algo-Sim › Arrays & Hashing
Majority Element
Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input
Boyer–Moore voting: keep one candidate and a count; differing values cancel in pairs and the majority survives.
Problem
An array nums of length n contains one value that occurs more than n / 2 times. Return that value. Can you do it in linear time with only O(1) extra space?
Constraints
- 1 ≤ n ≤ 5 · 10⁴
- -10⁹ ≤ nums[i] ≤ 10⁹
- A majority element always exists
- Follow-up: O(n) time and O(1) space
Edge cases to test
- A single element
- The majority is exactly ⌊n / 2⌋ + 1 times
- Negative values
Follow-up questions
- What if a majority might not exist?
- Run Boyer–Moore, then do a second pass to count the candidate and check it really appears more than n / 2 times: still O(n), O(1).
- What about every value appearing more than n / 3 times?
- Keep two candidates and two counts (LC 229); at most two values can qualify. Verify with a second pass: O(n) time, O(1) space.
Solution
Java
public int majorityElement(int[] nums) {
int candidate = 0, count = 0;
for (int x : nums) {
if (count == 0) candidate = x;
count += (x == candidate) ? 1 : -1;
}
return candidate;
}Python
def majority_element(nums):
candidate, count = 0, 0
for x in nums:
if count == 0: candidate = x
count += 1 if x == candidate else -1
return candidateC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
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;
}
};
More Arrays & Hashing problems
- Contains Duplicate (Easy)
- Valid Anagram (Easy)
- Two Sum (Easy)
- Group Anagrams (Medium)
- Top K Frequent Elements (Medium)
- Encode and Decode Strings (Medium)
- Product of Array Except Self (Medium)
- Longest Consecutive Sequence (Medium)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Subarray Sum Equals K (Medium)
- Design HashMap (Easy)