Majority Element
Given an array nums of size n, return the majority element — the element that appears strictly more than ⌊n / 2⌋ times, i.e. on more than half of all positions. You may assume that the majority element always exists in the array.
- n == nums.length
- 1 <= n <= 5 × 10⁴
- -10⁹ <= nums[i] <= 10⁹
- The majority element always exists in the input
nums = [3,2,3]3nums = [2,2,1,1,1,2,2]2nums = [2,2,1,2]2nums = [1]1Finding the Majority Element is about identifying the value that appears strictly more than half the time in an array. This element is so dominant that it effectively "outvotes" every other number combined.
The most intuitive solution is to sort the array. If a majority element exists, it must occupy the middle index (n // 2) because it spans more than 50% of the array's length.
nums.sort()
return nums[len(nums) // 2]We can count the frequency of every number using a map. This is faster than sorting but requires extra space to store the counts.
counts = {}
for num in nums:
counts[num] = counts.get(num, 0) + 1
if counts[num] > len(nums) // 2:
return numThe Hash Map is fast but uses extra memory. The core insight is that the majority element appears more times than all other numbers combined. This means if we let different numbers "knock each other out," the majority element is guaranteed to be the last one left standing.
We maintain a "candidate" and a "strength" counter.
- If strength is 0, we adopt the current number as our candidate.
- If the current number matches the candidate, we add 1 to strength.
- If it's different, we subtract 1.
Because the majority element occurs > 50% of the time, it will survive all cancellations to remain the final candidate.
candidate = None
count = 0
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate