Majority Element
Last Updated :
14 Aug, 2024
Find the majority element in the array. A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).
Examples :
Input : arr[] = {3, 9, 2, 9, 2, 9, 9}
Output : 9
Explanation: n = 7. Note that 9 appear more 4 times which is more than 7/2 times
Input : arr[] = {3}
Output : 3
Explanation: Appears more than n/2 times
Input : A[] = {3, 3, 4, 2, 4, 4, 2, 4}
Output : No Majority Element
Explanation: There is no element whose frequency is greater than the half of the size of the array size.
Naive Approach (O(n^2) time and O(1) Space)
The basic solution is to have two loops and keep track of the maximum count for all different elements. If the maximum count becomes greater than n/2 then break the loops and return the element having the maximum count. If the maximum count doesn’t become more than n/2 then the majority element doesn’t exist.
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the Majority element
// in a vector
void findMajority(const vector<int>& arr) {
int n = arr.size();
int maxCount = 0;
int index = -1; // sentinels
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
// update maxCount if count of
// current element is greater
if (count > maxCount) {
maxCount = count;
index = i;
}
}
// if maxCount is greater than n/2,
// return the corresponding element
if (maxCount > n / 2)
cout << arr[index] << endl;
else
cout << "No Majority Element" << endl;
}
// Driver code
int main() {
vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
// Function calling
findMajority(arr);
return 0;
}
C
#include <stdio.h>
// Function to find Majority element
// in an array
void findMajority(int arr[], int n)
{
int maxCount = 0;
int index = -1; // sentinels
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
// update maxCount if count of
// current element is greater
if (count > maxCount) {
maxCount = count;
index = i;
}
}
// if maxCount is greater than n/2
// return the corresponding element
if (maxCount > n / 2)
printf("%d\n", arr[index]);
else
printf("No Majority Element\n");
}
// Driver code
int main()
{
int arr[] = { 1, 1, 2, 1, 3, 5, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function calling
findMajority(arr, n);
return 0;
}
// This code is contributed by Vaibhav Saroj.
Java
// Java program to find Majority
// element in an array
import java.io.*;
class GFG {
// Function to find Majority element
// in an array
static void findMajority(int arr[], int n)
{
int maxCount = 0;
int index = -1; // sentinels
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
// update maxCount if count of
// current element is greater
if (count > maxCount) {
maxCount = count;
index = i;
}
}
// if maxCount is greater than n/2
// return the corresponding element
if (maxCount > n / 2)
System.out.println(arr[index]);
else
System.out.println("No Majority Element");
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 1, 2, 1, 3, 5, 1 };
int n = arr.length;
// Function calling
findMajority(arr, n);
}
// This code is contributed by ajit.
}
Python
# Python3 program to find Majority
# element in an array
# Function to find Majority
# element in an array
def findMajority(arr, n):
maxCount = 0
index = -1 # sentinels
for i in range(n):
count = 1
# here we compare the element in
# ith position with i+1th position
for j in range(i+1, n):
if(arr[i] == arr[j]):
count += 1
# update maxCount if count of
# current element is greater
if(count > maxCount):
maxCount = count
index = i
# if maxCount is greater than n/2
# return the corresponding element
if (maxCount > n//2):
print(arr[index])
else:
print("No Majority Element")
# Driver code
if __name__ == "__main__":
arr = [1, 1, 2, 1, 3, 5, 1]
n = len(arr)
# Function calling
findMajority(arr, n)
# This code is contributed
# by ChitraNayal
C#
// C# program to find Majority
// element in an array
using System;
public class GFG {
// Function to find Majority element
// in an array
static void findMajority(int[] arr, int n)
{
int maxCount = 0;
int index = -1; // sentinels
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
// update maxCount if count of
// current element is greater
if (count > maxCount) {
maxCount = count;
index = i;
}
}
// if maxCount is greater than n/2
// return the corresponding element
if (maxCount > n / 2)
Console.WriteLine(arr[index]);
else
Console.WriteLine("No Majority Element");
}
// Driver code
static public void Main()
{
int[] arr = { 1, 1, 2, 1, 3, 5, 1 };
int n = arr.Length;
// Function calling
findMajority(arr, n);
}
// This code is contributed by Tushil..
}
Javascript
// Javascript program to find Majority
// element in an array
// Function to find Majority element
// in an array
function findMajority(arr, n)
{
let maxCount = 0;
let index = -1; // sentinels
for(let i = 0; i < n; i++)
{
let count = 0;
for(let j = 0; j < n; j++)
{
if (arr[i] == arr[j])
count++;
}
// Update maxCount if count of
// current element is greater
if (count > maxCount)
{
maxCount = count;
index = i;
}
}
// If maxCount is greater than n/2
// return the corresponding element
if (maxCount > n / 2)
console.log(arr[index]);
else
console.log("No Majority Element");
}
// Driver code
let arr = [ 1, 1, 2, 1, 3, 5, 1 ];
let n = arr.length;
// Function calling
findMajority(arr, n);
// This code is contributed by suresh07
PHP
<?php
// PHP program to find Majority
// element in an array
// Function to find Majority element
// in an array
function findMajority($arr, $n)
{
$maxCount = 0;
$index = -1; // sentinels
for($i = 0; $i < $n; $i++)
{
$count = 0;
for($j = 0; $j < $n; $j++)
{
if($arr[$i] == $arr[$j])
$count++;
}
// update maxCount if count of
// current element is greater
if($count > $maxCount)
{
$maxCount = $count;
$index = $i;
}
}
// if maxCount is greater than n/2
// return the corresponding element
if ($maxCount > $n/2)
echo $arr[$index] . "\n";
else
echo "No Majority Element" . "\n";
}
// Driver code
$arr = array(1, 1, 2, 1, 3, 5, 1);
$n = sizeof($arr);
// Function calling
findMajority($arr, $n);
// This code is contributed
// by Akanksha Rai
Time Complexity: O(n*n), A nested loop is needed where both the loops traverse the array from start to end.
Auxiliary Space: O(1), No extra space is required.
This is a two-step process:
- The first step gives the element that may be the majority element in the array. If there is a majority element in an array, then this step will definitely return majority element, otherwise, it will return candidate for majority element.
- Check if the element obtained from the above step is the majority element. This step is necessary as there might be no majority element.
Follow the steps below to solve the given problem:
- Loop through each element and maintains a count of the majority element, and a majority index, maj_index
- If the next element is the same then increment the count if the next element is not the same then decrement the count.
- if the count reaches 0 then change the maj_index to the current element and set the count again to 1.
- Now again traverse through the array and find the count of the majority element found.
- If the count is greater than half the size of the array, print the element
- Else print that there is no majority element
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
/* Function to find the candidate for Majority */
int findCandidate(const vector<int>& arr) {
int maj_index = 0, count = 1;
int size = arr.size();
for (int i = 1; i < size; i++) {
if (arr[maj_index] == arr[i])
count++;
else
count--;
if (count == 0) {
maj_index = i;
count = 1;
}
}
return arr[maj_index];
}
/* Function to check if the candidate occurs
more than n/2 times */
bool isMajority(const vector<int>& arr, int cand) {
int count = 0;
int size = arr.size();
for (int i = 0; i < size; i++) {
if (arr[i] == cand)
count++;
}
return (count > size / 2);
}
/* Function to print Majority Element */
void printMajority(const vector<int>& arr) {
/* Find the candidate for Majority */
int cand = findCandidate(arr);
/* Print the candidate if it is Majority */
if (isMajority(arr, cand))
cout << " " << cand << " ";
else
cout << "No Majority Element";
}
/* Driver code */
int main() {
vector<int> arr = { 1, 3, 3, 1, 2 };
// Function calling
printMajority(arr);
return 0;
}
C
/* Program for finding out majority element in an array */
#include <stdio.h>
#define bool int
int findCandidate(int*, int);
bool isMajority(int*, int, int);
/* Function to print Majority Element */
void printMajority(int a[], int size)
{
/* Find the candidate for Majority*/
int cand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if (isMajority(a, size, cand))
printf(" %d ", cand);
else
printf("No Majority Element");
}
/* Function to find the candidate for Majority */
int findCandidate(int a[], int size)
{
int maj_index = 0, count = 1;
int i;
for (i = 1; i < size; i++) {
if (a[maj_index] == a[i])
count++;
else
count--;
if (count == 0) {
maj_index = i;
count = 1;
}
}
return a[maj_index];
}
/* Function to check if the candidate occurs more than n/2
* times */
bool isMajority(int a[], int size, int cand)
{
int i, count = 0;
for (i = 0; i < size; i++)
if (a[i] == cand)
count++;
if (count > size / 2)
return 1;
else
return 0;
}
/* Driver code */
int main()
{
int a[] = { 1, 3, 3, 1, 2 };
int size = (sizeof(a)) / sizeof(a[0]);
// Function call
printMajority(a, size);
getchar();
return 0;
}
Java
/* Program for finding out majority element in an array */
class MajorityElement {
/* Function to print Majority Element */
void printMajority(int a[], int size)
{
/* Find the candidate for Majority*/
int cand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if (isMajority(a, size, cand))
System.out.println(" " + cand + " ");
else
System.out.println("No Majority Element");
}
/* Function to find the candidate for Majority */
int findCandidate(int a[], int size)
{
int maj_index = 0, count = 1;
int i;
for (i = 1; i < size; i++) {
if (a[maj_index] == a[i])
count++;
else
count--;
if (count == 0) {
maj_index = i;
count = 1;
}
}
return a[maj_index];
}
/* Function to check if the candidate occurs more
than n/2 times */
boolean isMajority(int a[], int size, int cand)
{
int i, count = 0;
for (i = 0; i < size; i++) {
if (a[i] == cand)
count++;
}
if (count > size / 2)
return true;
else
return false;
}
/* Driver code */
public static void main(String[] args)
{
MajorityElement majorelement
= new MajorityElement();
int a[] = new int[] { 1, 3, 3, 1, 2 };
// Function call
int size = a.length;
majorelement.printMajority(a, size);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Program for finding out majority element in an array
# Function to find the candidate for Majority
def findCandidate(A):
maj_index = 0
count = 1
for i in range(len(A)):
if A[maj_index] == A[i]:
count += 1
else:
count -= 1
if count == 0:
maj_index = i
count = 1
return A[maj_index]
# Function to check if the candidate occurs more than n/2 times
def isMajority(A, cand):
count = 0
for i in range(len(A)):
if A[i] == cand:
count += 1
if count > len(A)/2:
return True
else:
return False
# Function to print Majority Element
def printMajority(A):
# Find the candidate for Majority
cand = findCandidate(A)
# Print the candidate if it is Majority
if isMajority(A, cand) == True:
print(cand)
else:
print("No Majority Element")
# Driver code
A = [1, 3, 3, 1, 2]
# Function call
printMajority(A)
C#
// C# Program for finding out majority element in an array
using System;
class GFG {
/* Function to print Majority Element */
static void printMajority(int[] a, int size)
{
/* Find the candidate for Majority*/
int cand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if (isMajority(a, size, cand))
Console.Write(" " + cand + " ");
else
Console.Write("No Majority Element");
}
/* Function to find the candidate for Majority */
static int findCandidate(int[] a, int size)
{
int maj_index = 0, count = 1;
int i;
for (i = 1; i < size; i++) {
if (a[maj_index] == a[i])
count++;
else
count--;
if (count == 0) {
maj_index = i;
count = 1;
}
}
return a[maj_index];
}
// Function to check if the candidate
// occurs more than n/2 times
static bool isMajority(int[] a, int size, int cand)
{
int i, count = 0;
for (i = 0; i < size; i++) {
if (a[i] == cand)
count++;
}
if (count > size / 2)
return true;
else
return false;
}
// Driver Code
public static void Main()
{
int[] a = { 1, 3, 3, 1, 2 };
int size = a.Length;
// Function call
printMajority(a, size);
}
}
// This code is contributed by Sam007
Javascript
// Javascript Program for finding out majority element in an
// array
/* Function to print Majority Element */
function printMajority(a, size)
{
/* Find the candidate for Majority*/
let cand = findCandidate(a, size);
/* Print the candidate if it is Majority*/
if (isMajority(a, size, cand))
console.log(" " + cand + " ");
else
console.log("No Majority Element");
}
/* Function to find the candidate for Majority */
function findCandidate(a, size)
{
let maj_index = 0, count = 1;
let i;
for (i = 1; i < size; i++) {
if (a[maj_index] == a[i])
count++;
else
count--;
if (count == 0) {
maj_index = i;
count = 1;
}
}
return a[maj_index];
}
// Function to check if the candidate
// occurs more than n/2 times
function isMajority(a, size, cand)
{
let i, count = 0;
for (i = 0; i < size; i++) {
if (a[i] == cand)
count++;
}
if (count > parseInt(size / 2, 10))
return true;
else
return false;
}
let a = [ 1, 3, 3, 1, 2 ];
let size = a.length;
// Function call
printMajority(a, size);
PHP
<?php
// PHP Program for finding out majority
// element in an array
// Function to find the candidate
// for Majority
function findCandidate($a, $size)
{
$maj_index = 0;
$count = 1;
for ($i = 1; $i < $size; $i++)
{
if ($a[$maj_index] == $a[$i])
$count++;
else
$count--;
if ($count == 0)
{
$maj_index = $i;
$count = 1;
}
}
return $a[$maj_index];
}
// Function to check if the candidate
// occurs more than n/2 times
function isMajority($a, $size, $cand)
{
$count = 0;
for ($i = 0; $i < $size; $i++)
if ($a[$i] == $cand)
$count++;
if ($count > $size / 2)
return 1;
else
return 0;
}
// Function to print Majority Element
function printMajority($a, $size)
{
/* Find the candidate for Majority*/
$cand = findCandidate($a, $size);
/* Print the candidate if it is Majority*/
if (isMajority($a, $size, $cand))
echo " ", $cand, " ";
else
echo "No Majority Element";
}
// Driver Code
$a = array(1, 3, 3, 1, 2);
$size = sizeof($a);
// Function calling
printMajority($a, $size);
// This code is contributed by jit_t
?>
OutputNo Majority Element
Illustration:
arr[] = {3, 4, 3, 2, 4, 4, 4, 4}, n = 8
maj_index = 0, count = 1
At i = 1: arr[maj_index] != arr[i]
- count = count – 1 = 1 – 1 = 0
- now count == 0 then:
- maj_index = i = 1
- count = count + 1 = 0 + 1 = 1
At i = 2: arr[maj_index] != arr[i]
- count = count – 1 = 1 – 1 = 0
- now count == 0 then:
- maj_index = i = 2
- count = count + 1 = 0 + 1 = 1
At i = 3: arr[maj_index] != arr[i]
- count = count – 1 = 1 – 1 = 0
- now count == 0 then:
- maj_index = i = 3
- count = count + 1 = 0 + 1 = 1
At i = 4: arr[maj_index] != arr[i]
- count = count – 1 = 1 – 1 = 0
- now count == 0 then:
- maj_index = i = 4
- count = count + 1 = 0 + 1 = 1
At i = 5: arr[maj_index] == arr[i]
- count = count + 1 = 1 + 1 = 2
At i = 6: arr[maj_index] == arr[i]
- count = count + 1 = 2 + 1 = 3
At i = 7: arr[maj_index] == arr[i]
- count = count + 1 = 3 + 1 = 4
Therefore, the arr[maj_index] may be the possible candidate for majority element.
Now, Again traverse the array and check whether arr[maj_index] is the majority element or not.
arr[maj_index] is 4
4 occurs 5 times in the array therefore 4 is our majority element.
Time Complexity: O(n), As two traversal of the array, is needed, so the time complexity is linear.
Auxiliary Space: O(1), As no extra space is required.
Further Optimization : In case vote count by the voting algorithm becomes 0 at the end, then we do not need to call isMajority() as this element would never be the mojority element.
Using Hashing (O(n) time and O(n) Space)
In Hashtable(key-value pair), at value, maintain a count for each element(key), and whenever the count is greater than half of the array length, return that key(majority element).
Illustration:
arr[] = {3, 4, 3, 2, 4, 4, 4, 4}, n = 8
Create a hashtable for the array
3 -> 2
4 -> 5
2 -> 1
Now traverse the hashtable
- Count for 3 is 2, which is less than n/2 (4) therefore it can’t be the majority element.
- Count for 4 is 5, which is greater than n/2 (4) therefore 4 is the majority element.
Hence, 4 is the majority element.
Follow the steps below to solve the given problem:
- Create a hashmap to store a key-value pair, i.e. element-frequency pair.
- Traverse the array from start to end.
- For every element in the array, insert the element in the hashmap if the element does not exist as a key, else fetch the value of the key ( array[i] ), and increase the value by 1
- If the count is greater than half then print the majority element and break.
- If no majority element is found print “No Majority element”
Below is the implementation of the above idea:
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
void findMajority(const vector<int>& arr) {
// Find frequencies
unordered_map<int, int> m;
for (int num : arr)
m[num]++;
// Find max Frequency item
int maxFreq = 0;
int res = -1;
for (auto i : m) {
if (i.second > maxFreq) {
maxFreq = i.second;
res = i.first;
}
}
// Check for majority
if (maxFreq > arr.size() / 2)
cout << "Majority found: " << res << endl;
else
cout << "No Majority element" << endl;
}
int main() {
vector<int> arr = {2, 1, 2, 3, 3, 3, 3};
findMajority(arr);
return 0;
}
Java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GfG {
public static void findMajority(List<Integer> arr) {
// Find frequencies
Map<Integer, Integer> mp = new HashMap<>();
for (int num : arr) {
mp.put(num, mp.getOrDefault(num, 0) + 1);
}
// Find max Frequency item
int maxFreq = 0;
int res = -1;
for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
if (entry.getValue() > maxFreq) {
maxFreq = entry.getValue();
res = entry.getKey();
}
}
// Check for majority
if (maxFreq > arr.size() / 2) {
System.out.println("Majority found: " + res);
} else {
System.out.println("No Majority element");
}
}
public static void main(String[] args) {
List<Integer> arr = List.of(2); // Example input using List
findMajority(arr);
}
}
Python
def find_majority_element(arr):
# Find frequencies
mp = {}
for num in arr:
mp[num] = mp.get(num, 0) + 1
# Find max Frequency item
max_freq = 0
res = -1
for key, value in mp.items():
if value > max_freq:
max_freq = value
res = key
# Check for majority
if max_freq > len(arr) // 2:
print(f"Majority found: {res}")
else:
print("No Majority element")
if __name__ == "__main__":
arr = [2] # Example input using list
find_majority_element(arr)
C#
using System;
using System.Collections.Generic;
class GfG {
public static void FindMajority(List<int> arr) {
// Find frequencies
Dictionary<int, int> mp = new Dictionary<int, int>();
foreach (int num in arr) {
if (mp.ContainsKey(num))
mp[num]++;
else
mp[num] = 1;
}
// Find max Frequency item
int maxFreq = 0;
int res = -1;
foreach (var entry in mp) {
if (entry.Value > maxFreq) {
maxFreq = entry.Value;
res = entry.Key;
}
}
// Check for majority
if (maxFreq > arr.Count / 2)
Console.WriteLine("Majority found: " + res);
else
Console.WriteLine("No Majority element");
}
static void Main(string[] args) {
List<int> arr = new List<int> { 2 };
FindMajority(arr);
}
}
Javascript
function findMajority(arr) {
// Find frequencies
let mp = {};
for (let num of arr) {
mp[num] = (mp[num] || 0) + 1;
}
// Find max Frequency item
let maxFreq = 0;
let res = -1;
for (let key in mp) {
if (mp[key] > maxFreq) {
maxFreq = mp[key];
res = parseInt(key);
}
}
// Check for majority
if (maxFreq > arr.length / 2) {
console.log("Majority found: " + res);
} else {
console.log("No Majority element");
}
}
// Example usage
let arr = [2]; // Example input using array
findMajority(arr);
Time Complexity: O(n), One traversal of the array is needed, so the time complexity is linear.
Auxiliary Space: O(n), Since a hashmap requires linear space.
Using Sorting (O(n Log n) time and O(1) Space)
The idea is to sort the array. Sorting makes similar elements in the array adjacent, so traverse the array and update the count until the present element is similar to the previous one. If the frequency is more than half the size of the array, print the majority element.
Illustration:
arr[] = {3, 4, 3, 2, 4, 4, 4, 4}, n = 8
Array after sorting => arr[] = {2, 3, 3, 4, 4, 4, 4, 4}, count = 1
At i = 1:
- arr[i] != arr[i – 1] => arr[1] != arr[0]
- count is not greater than n/2, therefore reinitialise count with, count = 1
At i = 2:
- arr[i] == arr[i – 1] => arr[2] == arr[1] = 3
- count = count + 1 = 1 + 1 = 2
At i = 3
- arr[i] != arr[i – 1] => arr[3] != arr[2]
- count is not greater than n/2, therefore reinitialise count with, count = 1
At i = 4
- arr[i] == arr[i – 1] => arr[4] == arr[3] = 4
- count = count + 1 = 1 + 1 = 2
At i = 5
- arr[i] == arr[i – 1] => arr[5] == arr[4] = 4
- count = count + 1 = 2 + 1 = 3
At i = 6
- arr[i] == arr[i – 1] => arr[6] == arr[5] = 4
- count = count + 1 = 3 + 1 = 4
At i = 7
- arr[i] == arr[i – 1] => arr[7] == arr[6] = 4
- count = count + 1 = 4 + 1 = 5
- Therefore, the count of 4 is now greater than n/2.
Hence, 4 is the majority element.
Follow the steps below to solve the given problem:
- Sort the array and create a variable count and previous, prev = INT_MIN.
- Traverse the element from start to end.
- If the current element is equal to the previous element increase the count.
- Else set the count to 1.
- If the count is greater than half the size of the array, print the element as the majority element and break.
- If no majority element is found, print “No majority element”
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find Majority element
// in a vector
// it returns -1 if there is no majority element
int majorityElement(vector<int>& arr) {
int n = arr.size();
if (n == 1) return arr[0];
int cnt = 1;
// sort the array, O(n log n)
sort(arr.begin(), arr.end());
for (int i = 1; i < n; i++) {
if (arr[i - 1] == arr[i]) {
cnt++;
} else {
if (cnt > n / 2) {
return arr[i - 1];
}
cnt = 1;
}
}
// Check the last element
if (cnt > n / 2) {
return arr[n - 1];
}
// if no majority element, return -1
return -1;
}
// Driver code
int main() {
vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
// Function calling
cout << majorityElement(arr);
return 0;
}
Java
// Java program to find Majority
// element in an array
import java.io.*;
import java.util.*;
class GFG{
// Function to find Majority element
// in an array it returns -1 if there
// is no majority element
public static int majorityElement(int[] arr, int n)
{
// Sort the array in O(nlogn)
Arrays.sort(arr);
int count = 1, max_ele = -1,
temp = arr[0], ele = 0,
f = 0;
for(int i = 1; i <= n; i++)
{
// Increases the count if the
// same element occurs otherwise
// starts counting new element
if (temp == arr[i])
{
count++;
}
else
{
count = 1;
temp = arr[i];
}
// Sets maximum count and stores
// maximum occurred element so far
// if maximum count becomes greater
// than n/2 it breaks out setting
// the flag
if (max_ele < count)
{
max_ele = count;
ele = arr[i];
if (max_ele > (n / 2))
{
f = 1;
break;
}
}
}
// Returns maximum occurred element
// if there is no such element, returns -1
return (f == 1 ? ele : -1);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 1, 2, 1, 3, 5, 1 };
int n = 7;
System.out.println(majorityElement(arr, n));
}
}
// This code is contributed by RohitOberoi
Python
# Python3 program to find Majority
# element in an array
# Function to find Majority element
# in an array
# it returns -1 if there is no majority element
def majorityElement(arr, n) :
# sort the array in O(nlogn)
arr.sort()
count, max_ele, temp, f = 1, -1, arr[0], 0
for i in range(1, n) :
# increases the count if the same element occurs
# otherwise starts counting new element
if(temp == arr[i]) :
count += 1
else :
count = 1
temp = arr[i]
# sets maximum count
# and stores maximum occurred element so far
# if maximum count becomes greater than n/2
# it breaks out setting the flag
if(max_ele < count) :
max_ele = count
ele = arr[i]
if(max_ele > (n//2)) :
f = 1
break
# returns maximum occurred element
# if there is no such element, returns -1
if f == 1 :
return ele
else :
return -1
# Driver code
arr = [1, 1, 2, 1, 3, 5, 1]
n = len(arr)
# Function calling
print(majorityElement(arr, n))
# This code is contributed by divyeshrabadiya07
C#
// C# program to find Majority
// element in an array
using System;
class GFG
{
// Function to find Majority element
// in an array it returns -1 if there
// is no majority element
public static int majorityElement(int[] arr, int n)
{
// Sort the array in O(nlogn)
Array.Sort(arr);
int count = 1, max_ele = -1,
temp = arr[0], ele = 0,
f = 0;
for(int i = 1; i < n; i++)
{
// Increases the count if the
// same element occurs otherwise
// starts counting new element
if (temp == arr[i])
{
count++;
}
else
{
count = 1;
temp = arr[i];
}
// Sets maximum count and stores
// maximum occurred element so far
// if maximum count becomes greater
// than n/2 it breaks out setting
// the flag
if (max_ele < count)
{
max_ele = count;
ele = arr[i];
if (max_ele > (n / 2))
{
f = 1;
break;
}
}
}
// Returns maximum occurred element
// if there is no such element, returns -1
return (f == 1 ? ele : -1);
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 1, 1, 2, 1, 3, 5, 1 };
int n = 7;
Console.WriteLine(majorityElement(arr, n));
}
}
// This code is contributed by aashish1995
Javascript
// Javascript program to find Majority
// element in an array
// Function to find Majority element
// in an array it returns -1 if there
// is no majority element
function majorityElement(arr, n)
{
// Sort the array in O(nlogn)
arr.sort(function(a, b) { return a - b });
let count = 1, max_ele = -1, temp = arr[0], ele = 0,
f = 0;
for (let i = 1; i < n; i++) {
// Increases the count if the
// same element occurs otherwise
// starts counting new element
if (temp == arr[i]) {
count++;
}
else {
count = 1;
temp = arr[i];
}
// Sets maximum count and stores
// maximum occurred element so far
// if maximum count becomes greater
// than n/2 it breaks out setting
// the flag
if (max_ele < count) {
max_ele = count;
ele = arr[i];
if (max_ele > parseInt(n / 2, 10)) {
f = 1;
break;
}
}
}
// Returns maximum occurred element
// if there is no such element, returns -1
return (f == 1 ? ele : -1);
}
let arr = [ 1, 1, 2, 1, 3, 5, 1 ];
let n = 7;
console.log(majorityElement(arr, n));
Time Complexity: O(n log n), Sorting requires O(n log n) time complexity.
Auxiliary Space: O(1), As no extra space is required.
Please Login to comment...