25. Majority Element
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given an array arr[]
, find the majority element in the array. A majority element is an element that appears strictly more than arr.size() / 2
times.
If no such element exists, return -1
.
๐ Examples
Example 1:
Input:
arr[] = [1, 1, 2, 1, 3, 5, 1]
Output:
1
Explanation:
1
appears 4 times out of 7, which is more than 7/2. Hence, it is the majority element.
Example 2:
Input:
arr[] = [7]
Output:
7
Explanation:
The only element 7
appears once, which is more than 1/2. Hence, it is the majority element.
Example 3:
Input:
arr[] = [2, 13]
Output:
-1
Explanation:
No element occurs more than 2/2 times. Hence, no majority element.
๐ Constraints
$1 \leq \text{arr.size()} \leq 10^5$
$0 \leq \text{arr[i]} \leq 10^5$
โ
My Approach:
Boyer-Moore Voting Algorithm
This algorithm is optimal in both time and space. It works in two phases:
Candidate Selection โ Identify a potential majority candidate.
Validation Pass โ Count its frequency to confirm majority.
Algorithm Steps:
Initialize
count = 0
andcandidate = -1
.Traverse the array:
If
count == 0
, setcandidate = current element
.If current element equals
candidate
, incrementcount
.Else, decrement
count
.
After traversal, validate whether
candidate
actually occurs more thann/2
times.If yes, return
candidate
; else return-1
.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we traverse the array twice โ once to find candidate and once to validate.
Expected Auxiliary Space Complexity: O(1), as we only use a constant number of variables.
๐ก Code (C)
int majorityElement(int arr[], int n) {
int count=0,cand;
for(int i=0;i<n;i++){
if(!count) cand=arr[i];
count += arr[i]==cand ? 1 : -1;
}
count=0;
for(int i=0;i<n;i++) if(arr[i]==cand) count++;
return count>n/2 ? cand : -1;
}
๐ง Code (C++)
class Solution {
public:
int majorityElement(vector<int>& arr) {
int count = 0, candidate;
for (int num : arr) {
if (count == 0) candidate = num;
count += (num == candidate) ? 1 : -1;
}
count = 0;
for (int num : arr) if (num == candidate) count++;
return count > arr.size() / 2 ? candidate : -1;
}
};
๐งโ๐ป Code (Java)
class Solution {
static int majorityElement(int[] a) {
int cand=0, count=0;
for (int v : a) {
if (count == 0) cand = v;
count += v == cand ? 1 : -1;
}
count = 0;
for (int v : a) if (v == cand) count++;
return count > a.length / 2 ? cand : -1;
}
}
๐ Code (Python)
class Solution:
def majorityElement(self, a):
count = cand = 0
for v in a:
if not count:
cand = v
count += 1 if v == cand else -1
return cand if sum(1 for v in a if v == cand) > len(a)//2 else -1
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions? โ Letโs learn and grow together!
โญ If this helped you, don't forget to star the repository! โญ
๐Visitor Count
Last updated