Understanding the Problem
We are given an array of integers, and our goal is to find the majority element—if it exists. But what exactly is a majority element?
A majority element is an element that appears more than n/2 times in the array, where n is the total number of elements. If no such element exists, we return -1.
Approach to Solve the Problem
Step-by-step Explanation Using an Example
Let’s consider the example: [3, 3, 3, 2, 3, 3]
Here, n = 6, so to qualify as a majority, an element must appear more than 6/2 = 3 times, i.e., at least 4 times.
- Count of 3 = 5 → meets the condition
- Count of 2 = 1 → does not qualify
So, the answer is 3.
Step-by-step Plan to Solve It
- Use the Boyer-Moore Voting Algorithm to identify a candidate.
- Verify if the candidate actually occurs more than n/2 times.
- If yes, return the candidate; else, return -1.
Intuitive Explanation
Think of it like a voting game. Every time an element agrees with our current "leader", we give it a vote. When it disagrees, we take away a vote. If we run out of votes (count becomes 0), we choose a new leader.
In the end, if there’s a true majority, it will have survived all the challenges and still be the leader.
Edge Cases to Handle
- Empty Array: No elements → return
-1
- Single Element: [5] → 5 is the majority (only one element)
- No Majority Element: [1, 2, 3, 4] → all are unique → return
-1
- Tie Situation: [1, 1, 2, 2, 3, 3] → no one has > n/2 count → return
-1
Why This Works
Because non-majority elements cancel each other out, only the true majority can remain standing after the count balancing. If no such element exists, the second pass will filter it out.