Day 6 - Majority Element II
π Day 6. Majority Element II π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
You are given an array of integers arr[] where each number represents a vote for a candidate. Return the candidates that have votes greater than one-third of the total votes. If there's no majority vote, return an empty array.
Note: The answer should be returned in an increasing order.
π Example Walkthrough:
Input:
arr[] = [2, 1, 5, 5, 5, 5, 6, 6, 6, 6, 6]
Output:
[5, 6]
Explanation:
5 and 6 occur more than n / 3 times in the array.
Input:
arr[] = [1, 2, 3, 4, 5]
Output:
[]
Explanation:
No candidate occurs more than n / 3 times.
Constraints:
1 <= arr.size() <= 10^6-10^9 <= arr[i] <= 10^9
π― My Approach:
Boyer-Moore Voting Algorithm:
The problem can be efficiently solved using the Boyer-Moore Voting Algorithm to find the top two candidates with the potential to exceed
n / 3votes.First, identify the two potential majority elements.
Then, verify their counts to ensure they actually exceed the threshold.
This approach reduces the problem to a linear pass through the array.
Steps:
Traverse the array to find two majority candidates (
num1andnum2) using count variables.Traverse again to count occurrences of the candidates and validate the result.
Ensure the final output is sorted to meet the problem requirements.
π Time and Auxiliary Space Complexityπ
Expected Time Complexity: O(n), where
nis the size of the array. The algorithm requires two linear scans of the array, making it efficient.Expected Auxiliary Space Complexity: O(1), as we use only a constant amount of additional space.
π Solution Code
Code (C)
Code (Cpp)
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