Algorithm Day98 - Majority Element
🧩 Problem
LeetCode 169 - Majority Element
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times.
You may assume that the majority element always exists in the array.
Example:
1 | Input: nums = [2,2,1,1,1,2,2] |
💡 Idea
There are multiple approaches:
- Sorting → The middle element is the majority.
- HashMap counting → Count frequencies.
- Boyer–Moore Majority Vote Algorithm → O(n) time, O(1) space (most optimal).
Boyer–Moore Explanation
We maintain a candidate and a count.
- If
countis 0, set the current number ascandidate. - If the current number equals
candidate, incrementcount; otherwise, decrementcount.
At the end,candidateis the majority element.
Example
1 | nums = [2,2,1,1,1,2,2] |
💻 Java Code
1 | class Solution { |
🧠 Complexity
- Time: O(n)
- Space: O(1)
🏁 Summary
The Boyer–Moore algorithm is elegant and efficient — it eliminates the need for extra storage by leveraging the majority element’s dominance in occurrence.