Majority Element II
LeetCode 229 · Medium · solution, intuition & step-by-step walkthrough
Count and keep values with count > n // 3.
This is how I solved Majority Element II (LeetCode 229), a medium problem from the Moore Voting pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Any value appearing more than n/3 times qualifies; there can be at most two. Counting every value with a Counter and filtering by the threshold is straightforward.
Approach
- 1
Count frequencies.
- 2
Keep each value whose count exceeds n // 3.
How I solved it
Counter filterPythonO(n) time · O(n) space
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n = len(nums)
mpp = Counter(nums)
res = []
for key,val in mpp.items():
if val>(n//3):
res.append(key)
return resMajority Element II — FAQ
What is the intuition behind Majority Element II?
Any value appearing more than n/3 times qualifies; there can be at most two. Counting every value with a Counter and filtering by the threshold is straightforward.
How do you solve Majority Element II (LeetCode 229)?
1. Count frequencies. 2. Keep each value whose count exceeds n // 3.
What is the time and space complexity of Majority Element II?
Time: O(n). Space: O(n). (Accepted approach: Counter filter.)
What are common mistakes in Majority Element II?
Extended Boyer–Moore (two candidates) does it in O(1) space.