EasyNo. 0169
Majority Element — LeetCode 169 Python Solution
- Pattern
- Sorting
- Topics
- Array, Hash Table, Divide and Conquer, Counting, Sorting
- On study lists
- Grind 75 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times.
Example
- Input
- nums = [3,2,3]
- Output
- 3
Python solution
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cnt = m = 0
for x in nums:
if cnt == 0:
m, cnt = x, 1
else:
cnt += 1 if m == x else -1
return mComplexity
- Time
- O(n)where n is the length of the array nums
- Space · auxiliary
- O(1)
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 169. Majority Element 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 |
|---|---|---|
| 0229 | Majority Element II | Medium |
| 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 169. Majority Element?
LeetCode 169. Majority Element is rated Easy on LeetCode.
- What is the time complexity of LeetCode 169. Majority Element?
The Python solution on this page runs in O(n), where n is the length of the array nums.
- What is the space complexity of LeetCode 169. Majority Element?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 169. Majority Element cover?
LeetCode 169. Majority Element is tagged Array, Hash Table, Divide and Conquer, Counting and Sorting on LeetCode.