MediumNo. 0229
Majority Element II — LeetCode 229 Python Solution
- Pattern
- Sorting
- Topics
- Array, Hash Table, Counting, Sorting
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Example
- Input
- nums = [3,2,3]
- Output
- [3]
Python solution
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n1 = n2 = 0
m1, m2 = 0, 1
for m in nums:
if m == m1:
n1 += 1
elif m == m2:
n2 += 1
elif n1 == 0:
m1, n1 = m, 1
elif n2 == 0:
m2, n2 = m, 1
else:
n1, n2 = n1 - 1, n2 - 1
return [m for m in [m1, m2] if nums.count(m) > len(nums) // 3]Complexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 229. Majority Element II is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0169 | Majority Element | Easy |
| 0347 | Top K Frequent Elements | Medium |
| 0594 | Longest Harmonious Subsequence | Easy |
| 0621 | Task Scheduler | Medium |
| 0692 | Top K Frequent Words | Medium |
| 0923 | 3Sum With Multiplicity | Medium |
Frequently asked questions
- How hard is LeetCode 229. Majority Element II?
LeetCode 229. Majority Element II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 229. Majority Element II?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 229. Majority Element II?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 229. Majority Element II cover?
LeetCode 229. Majority Element II is tagged Array, Hash Table, Counting and Sorting on LeetCode.