26. Majority Element II
β GFG solution to the Majority Element II problem: find all elements appearing more than n/3 times using Boyer-Moore Majority Vote algorithm. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array of integer arr[] where each number represents a vote to a candidate. Return the candidates that have votes greater than one-third of the total votes. If there's not a majority vote, return an empty array.
Note: The answer should be returned in an increasing format.
π Examples
Example 1
Input: arr[] = [2, 1, 5, 5, 5, 5, 6, 6, 6, 6, 6]
Output: [5, 6]
Explanation: 5 occurs 4 times and 6 occurs 5 times. Both appear more than n/3 = 11/3 = 3.67 times.
Hence, both 5 and 6 are majority elements.Example 2
Input: arr[] = [1, 2, 3, 4, 5]
Output: []
Explanation: The total number of votes are 5. No candidate occurs more than floor(5/3) = 1 time.
Since we need elements appearing more than n/3 times, no element qualifies.π Constraints
$1 \le \text{arr.size()} \le 10^6$
$1 \le \text{arr}[i] \le 10^5$
β
My Approach
The optimal approach uses the Boyer-Moore Majority Vote Algorithm extended for finding elements appearing more than n/3 times:
Boyer-Moore Voting Algorithm (Extended)
Key Insight:
At most 2 elements can appear more than n/3 times in an array.
We maintain two candidates and their counts during the voting phase.
Phase 1 - Candidate Selection:
Initialize two candidates
aandbwith different values, and their countscaandcb.For each element
x:If
xequals candidatea, incrementcaElse if
xequals candidateb, incrementcbElse if
cais 0, seta = xandca = 1Else if
cbis 0, setb = xandcb = 1Else decrement both
caandcb(voting against both candidates)
Phase 2 - Verification:
Reset counts and verify if the selected candidates actually appear more than n/3 times.
Count actual occurrences of candidates
aandbin the array.
Result Formation:
Add candidates to result if their count > n/3.
Sort the result for increasing order output.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We make two passes through the array - one for candidate selection and one for verification.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for storing two candidates and their counts.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated