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 : A[]={3, 3, 4, 2, 4, 4, 2, 4, 4}
Output : 4
Explanation: The frequency of 4 is 5 which is greater than the half of the size of the array size.
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:
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.
Illustration:
arr[] = {3, 4, 3, 2, 4, 4, 4, 4}, n = 8
For i = 0:
- count = 0
- Loop over the array, whenever an element is equal to arr[i] (is 3), increment count
- count of arr[i] is 2, which is less than n/2, hence it can’t be majority element.
For i = 1:
- count = 0
- Loop over the array, whenever an element is equal to arr[i] (is 4), increment count
- count of arr[i] is 5, which is greater than n/2 (i.e 4), hence it will be majority element.
Hence, 4 is the majority element.
Follow the steps below to solve the given problem:
- Create a variable to store the max count, count = 0
- Traverse through the array from start to end.
- For every element in the array run another loop to find the count of similar elements in the given array.
- If the count is greater than the max count update the max count and store the index in another variable.
- If the maximum count is greater than half the size of the array, print the element. Else print there is no majority element.
Below is the implementation of the above idea:
C++
// C++ program to find Majority
// element in an array
#include <bits/stdc++.h>
using namespace std;
// 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)
cout << arr[index] << endl;
else
cout << "No Majority Element" << endl;
}
// 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;
}
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.
}
Python3
# 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
<script>
// 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)
document.write(arr[index]);
else
document.write("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
</script>
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.
Insert elements in BST one by one and if an element is already present then increment the count of the node. At any stage, if the count of a node becomes more than n/2 then return.
Illustration:
Follow the steps below to solve the given problem:
- Create a binary search tree, if the same element is entered in the binary search tree the frequency of the node is increased.
- traverse the array and insert the element in the binary search tree.
- If the maximum frequency of any node is greater than half the size of the array, then perform an inorder traversal and find the node with a frequency greater than half
- Else print No majority Element.
Below is the implementation of the above idea:
C
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
int c;
struct node* left;
struct node* right;
};
struct node* newNode(int item) {
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->c = 1;
temp->left = NULL;
temp->right = NULL;
return temp;
}
struct node* insert(struct node* node, int key, int* ma) {
if (node == NULL) {
if (*ma == 0)
*ma = 1;
return newNode(key);
}
if (key < node->key)
node->left = insert(node->left, key, ma);
else if (key > node->key)
node->right = insert(node->right, key, ma);
else
node->c++;
*ma = (*ma > node->c) ? *ma : node->c;
return node;
}
void inorder(struct node* root, int s) {
if (root != NULL) {
inorder(root->left, s);
if (root->c > (s / 2))
printf("%d \n", root->key);
inorder(root->right, s);
}
}
int main() {
int a[] = { 1, 3, 3, 3, 2 };
int size = sizeof(a) / sizeof(a[0]);
struct node* root = NULL;
int ma = 0;
for (int i = 0; i < size; i++) {
root = insert(root, a[i], &ma);
}
if (ma > (size / 2))
inorder(root, size);
else
printf("No majority element\n");
return 0;
}
// This code is contributed by Vaibhav Saroj.
Java
// Java program to demonstrate insert
// operation in binary search tree.
import java.io.*;
class Node
{
int key;
int c = 0;
Node left,right;
}
class GFG{
static int ma = 0;
// A utility function to create a
// new BST node
static Node newNode(int item)
{
Node temp = new Node();
temp.key = item;
temp.c = 1;
temp.left = temp.right = null;
return temp;
}
// A utility function to insert a new node
// with given key in BST
static Node insert(Node node, int key)
{
// If the tree is empty,
// return a new node
if (node == null)
{
if (ma == 0)
ma = 1;
return newNode(key);
}
// Otherwise, recur down the tree
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
else
node.c++;
// Find the max count
ma = Math.max(ma, node.c);
// Return the (unchanged) node pointer
return node;
}
// A utility function to do inorder
// traversal of BST
static void inorder(Node root, int s)
{
if (root != null)
{
inorder(root.left, s);
if (root.c > (s / 2))
System.out.println(root.key + "\n");
inorder(root.right, s);
}
}
// Driver Code
public static void main(String[] args)
{
int a[] = { 1, 3, 3, 3, 2 };
int size = a.length;
Node root = null;
for(int i = 0; i < size; i++)
{
root = insert(root, a[i]);
}
// Function call
if (ma > (size / 2))
inorder(root, size);
else
System.out.println("No majority element\n");
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python3 program to demonstrate insert operation in binary
# search tree.
# class for creating node
class Node():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.count = 1 # count of number of times data is inserted in tree
# class for binary search tree
# it initialises tree with None root
# insert function inserts node as per BST rule
# and also checks for majority element
# if no majority element is found yet, it returns None
class BST():
def __init__(self):
self.root = None
def insert(self, data, n):
out = None
if (self.root == None):
self.root = Node(data)
else:
out = self.insertNode(self.root, data, n)
return out
def insertNode(self, currentNode, data, n):
if (currentNode.data == data):
currentNode.count += 1
if (currentNode.count > n//2):
return currentNode.data
else:
return None
elif (currentNode.data < data):
if (currentNode.right):
self.insertNode(currentNode.right, data, n)
else:
currentNode.right = Node(data)
elif (currentNode.data > data):
if (currentNode.left):
self.insertNode(currentNode.left, data, n)
else:
currentNode.left = Node(data)
# Driver code
# declaring an array
arr = [3, 2, 3]
n = len(arr)
# declaring None tree
tree = BST()
flag = 0
for i in range(n):
out = tree.insert(arr[i], n)
if (out != None):
print(arr[i])
flag = 1
break
if (flag == 0):
print("No Majority Element")
C#
// C# program to demonstrate insert
// operation in binary search tree.
using System;
public class Node
{
public int key;
public int c = 0;
public Node left,right;
}
class GFG{
static int ma = 0;
// A utility function to create a
// new BST node
static Node newNode(int item)
{
Node temp = new Node();
temp.key = item;
temp.c = 1;
temp.left = temp.right = null;
return temp;
}
// A utility function to insert a new node
// with given key in BST
static Node insert(Node node, int key)
{
// If the tree is empty,
// return a new node
if (node == null)
{
if (ma == 0)
ma = 1;
return newNode(key);
}
// Otherwise, recur down the tree
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
else
node.c++;
// Find the max count
ma = Math.Max(ma, node.c);
// Return the (unchanged) node pointer
return node;
}
// A utility function to do inorder
// traversal of BST
static void inorder(Node root, int s)
{
if (root != null)
{
inorder(root.left, s);
if (root.c > (s / 2))
Console.WriteLine(root.key + "\n");
inorder(root.right, s);
}
}
// Driver Code
static public void Main()
{
int[] a = { 1, 3, 3, 3, 2 };
int size = a.Length;
Node root = null;
for(int i = 0; i < size; i++)
{
root = insert(root, a[i]);
}
// Function call
if (ma > (size / 2))
inorder(root, size);
else
Console.WriteLine("No majority element\n");
}
}
// This code is contributed by rag2127
Javascript
<script>
// javascript program to demonstrate insert
// operation in binary search tree.
class Node {
constructor(){
this.key = 0;
this.c = 0;
this.left = null,
this.right = null;
}
}
var ma = 0;
// A utility function to create a
// new BST node
function newNode(item)
{
var temp = new Node();
temp.key = item;
temp.c = 1;
temp.left = temp.right = null;
return temp;
}
// A utility function to insert a new node
// with given key in BST
function insert(node , key) {
// If the tree is empty,
// return a new node
if (node == null) {
if (ma == 0)
ma = 1;
return newNode(key);
}
// Otherwise, recur down the tree
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
else
node.c++;
// Find the max count
ma = Math.max(ma, node.c);
// Return the (unchanged) node pointer
return node;
}
// A utility function to do inorder
// traversal of BST
function inorder(root , s) {
if (root != null) {
inorder(root.left, s);
if (root.c > (s / 2))
document.write(root.key + "\n");
inorder(root.right, s);
}
}
// Driver Code
var a = [ 1, 3, 3, 3, 2 ];
var size = a.length;
var root = null;
for (i = 0; i < size; i++) {
root = insert(root, a[i]);
}
// Function call
if (ma > (size / 2))
inorder(root, size);
else
document.write("No majority element\n");
// This code is contributed by gauravrajput1
</script>
C++14
// C++ program to demonstrate insert operation in binary
// search tree.
#include <bits/stdc++.h>
using namespace std;
struct node {
int key;
int c = 0;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node* newNode(int item)
{
struct node* temp
= (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->c = 1;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to insert a new node with given key in
// BST
struct node* insert(struct node* node, int key, int& ma)
{
// If the tree is empty, return a new node
if (node == NULL) {
if (ma == 0)
ma = 1;
return newNode(key);
}
// Otherwise, recur down the tree
if (key < node->key)
node->left = insert(node->left, key, ma);
else if (key > node->key)
node->right = insert(node->right, key, ma);
else
node->c++;
// find the max count
ma = max(ma, node->c);
// return the (unchanged) node pointer
return node;
}
// A utility function to do inorder traversal of BST
void inorder(struct node* root, int s)
{
if (root != NULL) {
inorder(root->left, s);
if (root->c > (s / 2))
printf("%d \n", root->key);
inorder(root->right, s);
}
}
// Driver Code
int main()
{
int a[] = { 1, 3, 3, 3, 2 };
int size = (sizeof(a)) / sizeof(a[0]);
struct node* root = NULL;
int ma = 0;
for (int i = 0; i < size; i++) {
root = insert(root, a[i], ma);
}
// Function call
if (ma > (size / 2))
inorder(root, size);
else
cout << "No majority element\n";
return 0;
}
Time Complexity: If a Binary Search Tree is used then time complexity will be O(n²). If a self-balancing-binary-search tree is used then it will be O(nlogn)
Auxiliary Space: O(n), As extra space is needed to store the array in the tree.
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.
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.
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++
// C++ Program for finding out
// majority element in an array
#include <bits/stdc++.h>
using namespace std;
/* Function to find the candidate for Majority */
int findCandidate(int a[], int size)
{
int maj_index = 0, count = 1;
for (int 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 count = 0;
for (int i = 0; i < size; i++)
if (a[i] == cand)
count++;
if (count > size / 2)
return 1;
else
return 0;
}
/* 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))
cout << " " << cand << " ";
else
cout << "No Majority Element";
}
/* Driver code */
int main()
{
int a[] = { 1, 3, 3, 1, 2 };
int size = (sizeof(a)) / sizeof(a[0]);
// Function calling
printMajority(a, size);
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
Python3
# 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
<script>
// 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))
document.write(" " + cand + " ");
else
document.write("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);
// This code is contributed by rameshtravel07.
</script>
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
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.
Majority Element Using Hashing:
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++
/* C++ program for finding out majority
element in an array */
#include <bits/stdc++.h>
using namespace std;
void findMajority(int arr[], int size)
{
unordered_map<int, int> m;
for(int i = 0; i < size; i++)
m[arr[i]]++;
int count = 0;
for(auto i : m)
{
if(i.second > size / 2)
{
count =1;
cout << "Majority found :- " << i.first<<endl;
break;
}
}
if(count == 0)
cout << "No Majority element" << endl;
}
// Driver code
int main()
{
int arr[] = {2, 2, 2, 2, 5, 5, 2, 3, 3};
int n = sizeof(arr) / sizeof(arr[0]);
// Function calling
findMajority(arr, n);
return 0;
}
// This code is contributed by codeMan_d
C
#include <stdio.h>
#include <stdlib.h>
void findMajority(int arr[], int size)
{
int i, j;
int count = 0;
for(i = 0; i < size; i++)
{
int current = arr[i];
int freq = 0;
for(j = 0; j < size; j++)
{
if(arr[j] == current)
{
freq++;
}
}
if(freq > size / 2)
{
count = 1;
printf("Majority found :- %d\n", current);
break;
}
}
if(count == 0)
{
printf("No Majority element\n");
}
}
// Driver code
int main()
{
int arr[] = {2, 2, 2, 2, 5, 5, 2, 3, 3};
int n = sizeof(arr) / sizeof(arr[0]);
// Function calling
findMajority(arr, n);
return 0;
}
Java
import java.util.HashMap;
/* Program for finding out majority element in an array */
class MajorityElement
{
private static void findMajority(int[] arr)
{
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int count=0;
for(int i = 0; i < arr.length; i++)
{
if (map.containsKey(arr[i]))
{
count = map.get(arr[i]) +1;
map.put(arr[i], count);
}
else
{
map.put(arr[i],1);
}
if(map.get(arr[i]) > arr.length /2)
{
System.out.println("Majority found :- " + arr[i]);
return;
}
}
System.out.println(" No Majority element");
}
/* Driver program to test the above functions */
public static void main(String[] args)
{
int a[] = new int[]{2,2,2,2,5,5,2,3,3};
findMajority(a);
}
}
// Improved By Karan Bajaj
// This code is contributed by karan malhotra
Python3
# Python3 program for finding out majority
# element in an array
def findMajority(arr, size):
m = {}
for i in range(size):
if arr[i] in m:
m[arr[i]] += 1
else:
m[arr[i]] = 1
is_majority_present = False
for key in m:
if m[key] > size / 2:
is_majority_present = True
print("Majority found :-",key)
break
if not is_majority_present:
print("No Majority element")
# Driver code
arr = [2, 2, 2, 2, 5, 5, 2, 3, 3]
n = len(arr)
# Function calling
findMajority(arr, n)
# This code is contributed by ankush_953
C#
// C# Program for finding out majority
// element in an array
using System;
using System.Collections.Generic;
class GFG
{
private static void findMajority(int[] arr)
{
Dictionary<int,
int> map = new Dictionary<int,
int>();
for (int i = 0; i < arr.Length; i++)
{
if (map.ContainsKey(arr[i]))
{
int count = map[arr[i]] + 1;
if (count > arr.Length / 2)
{
Console.WriteLine("Majority found :- " +
arr[i]);
return;
}
else
{
map[arr[i]] = count;
}
}
else
{
map[arr[i]] = 1;
}
}
Console.WriteLine(" No Majority element");
}
// Driver Code
public static void Main(string[] args)
{
int[] a = new int[]{2, 2, 2, 2,
5, 5, 2, 3, 3};
findMajority(a);
}
}
// This code is contributed by Shrikant13
Javascript
<script>
// Javascript program for the above approach
function findMajority(arr)
{
let map = new Map();
for(let i = 0; i < arr.length; i++) {
if (map.has(arr[i])) {
let count = map.get(arr[i]) +1;
if (count > arr.length /2) {
document.write("Majority found :- " + arr[i]);
return;
} else
map.set(arr[i], count);
}
else
map.set(arr[i],1);
}
document.write(" No Majority element");
}
// Driver Code
let a = [ 2,2,2,2,5,5,2,3,3 ];
findMajority(a);
// This code is contributed by splevel62.
</script>
OutputMajority found :- 2
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.
Majority Element Using Sorting:
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++
// C++ program to find Majority
// element in an array
#include <bits/stdc++.h>
using namespace std;
// Function to find Majority element
// in an array
// it returns -1 if there is no majority element
int majorityElement(int *arr, int n)
{
if (n == 1) return arr[0];
int cnt = 1;
// sort the array, o(nlogn)
sort(arr, arr + n);
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;
}
}
// if no majority element, return -1
return -1;
}
// Driver code
int main()
{
int arr[] = {1, 1, 2, 1, 3, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
// Function calling
cout<<majorityElement(arr, n);
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
Python3
# 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
<script>
// 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;
document.write(majorityElement(arr, n));
</script>
Time Complexity: O(nlogn), Sorting requires O(n log n) time complexity.
Auxiliary Space: O(1), As no extra space is required.
The idea is to use the divide and conquer strategy to identify the majority element in an array using a recursive approach.
Majority Element Using Recursive Approach:
In this recursive approach, we divide the array into halves until we reach base cases where the array has only one element. Then, we combine the majority elements obtained from the left and right halves to find the overall majority element of the entire array.
Illustration:
Consider an array arr[] = {3, 4, 3, 2, 4, 4, 4, 4} with n = 8.
Split the array into two halves: left half arr_left[] = {3, 4, 3, 2} and right half arr_right[] = {4, 4, 4, 4}.
Recursively find the majority elements of both halves.
Combine the majority elements obtained from both halves.
Check if the combined majority element appears more than n/2 times in the entire array.
Follow the steps below to solve the given problem using a recursive approach:
Define a recursive function findMajorityUtil that takes an array arr[], its lower index low, and upper index high as input parameters.
If the array has only one element (low == high), return that element as the majority element.
Divide the array into two halves and recursively find the majority elements of both halves.
Combine the majority elements obtained from both halves.
Count the occurrences of the combined majority element in the entire array.
Return the combined majority element if it appears more than n/2 times; otherwise, return -1.
Follow the steps below to solve the given problem:
- Define a function “countOccurrences” which takes an array “arr”, its size “n”, and an integer “num” as input parameters. This function counts the number of occurrences of the given integer in the array and returns the count. And the initial count is 0.
- Then we’ll define a recursive function “findMajorityUtil” that takes an array, its lower “low” and upper “high” indices as input parameters. This function has the following steps:
- Check if the array has only one element (base case). If yes, return that element.
- Divide the array into two equal parts, left and right by finding the mid index.
- Recursively find the majority element in the left part and right part.
- If both the left and right parts have the same majority elements, then return that element.
- Count the total number of occurrences of the left and right majority elements in the entire array.
- Return the element that occurs more than n/2 times.
- Define a function “findMajority” which takes an array “arr” and its size “n” as input parameters. This function calls the “findMajorityUtil” function with the array and its indices and prints the majority element if it exists; otherwise, it will print “No Majority Element”.
- The “main” function will initialize an array “arr” and size “n”. It will call the “findMajority” function with these parameters.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the occurrences
int countOccurrences(int arr[], int n, int num) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == num)
count++;
}
return count;
}
// Function to find the majority element
// using recursion
int findMajorityUtil(int arr[], int low, int high) {
// Base case: single element array
if (low == high)
return arr[low];
// Divide the array into left
// and right halves
int mid = (low + high) / 2;
int leftMajority = findMajorityUtil(arr, low, mid);
int rightMajority = findMajorityUtil(arr, mid+1, high);
// If left and right halves have the
// same majority element
if (leftMajority == rightMajority)
return leftMajority;
// Count the occurrences of the
// majority element in entire array
int leftCount = countOccurrences(arr, high-low+1, leftMajority);
int rightCount = countOccurrences(arr, high-low+1, rightMajority);
// Return the element that occurs
// more than n/2 times
if (leftCount > (high-low+1) / 2)
return leftMajority;
if (rightCount > (high-low+1) / 2)
return rightMajority;
// No majority element
return -1;
}
// Function to find the majority element
void findMajority(int arr[], int n) {
int majority = findMajorityUtil(arr, 0, n-1);
if (majority != -1)
cout << majority << endl;
else
cout << "No Majority Element" << endl;
}
// Driver Code
int main() {
int arr[] = {1, 3, 3, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
findMajority(arr, n);
return 0;
}
C
#include <stdio.h>
int countOccurrences(int arr[], int n, int num) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == num)
count++;
}
return count;
}
int findMajorityUtil(int arr[], int low, int high) {
// Base case: single element array
if (low == high)
return arr[low];
// Divide the array into left
// and right halves
int mid = (low + high) / 2;
int leftMajority = findMajorityUtil(arr, low, mid);
int rightMajority = findMajorityUtil(arr, mid+1, high);
// If left and right halves have the
//same majority element
if (leftMajority == rightMajority)
return leftMajority;
// Count the occurrences of the majority
// element in the entire array
int leftCount = countOccurrences(arr, high-low+1, leftMajority);
int rightCount = countOccurrences(arr, high-low+1, rightMajority);
// Return the element that occurs
// more than n/2 times
if (leftCount > (high-low+1) / 2)
return leftMajority;
if (rightCount > (high-low+1) / 2)
return rightMajority;
// No majority element
return -1;
}
void findMajority(int arr[], int n) {
int majority = findMajorityUtil(arr, 0, n-1);
if (majority != -1)
printf("%d\n", majority);
else
printf("No Majority Element\n");
}
int main() {
int arr[] = {1, 3, 3, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
findMajority(arr, n);
return 0;
}
Java
import java.util.*;
public class MajorityElement {
// Function to count the occurrences
public static int countOccurrences(int[] arr, int n, int num) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == num)
count++;
}
return count;
}
// Function to find the majority element using recursion
public static int findMajorityUtil(int[] arr, int low, int high) {
// Base case: single element array
if (low == high)
return arr[low];
// Divide the array into left and right halves
int mid = (low + high) / 2;
int leftMajority = findMajorityUtil(arr, low, mid);
int rightMajority = findMajorityUtil(arr, mid + 1, high);
// If left and right halves have the same majority element
if (leftMajority == rightMajority)
return leftMajority;
// Count the occurrences of the majority element in entire array
int leftCount = countOccurrences(arr, high - low + 1, leftMajority);
int rightCount = countOccurrences(arr, high - low + 1, rightMajority);
// Return the element that occurs more than n/2 times
if (leftCount > (high - low + 1) / 2)
return leftMajority;
if (rightCount > (high - low + 1) / 2)
return rightMajority;
// No majority element
return -1;
}
// Function to find the majority element
public static void findMajority(int[] arr, int n) {
int majority = findMajorityUtil(arr, 0, n - 1);
if (majority != -1)
System.out.println(majority);
else
System.out.println("No Majority Element");
}
// Driver Code
public static void main(String[] args) {
int[] arr = {1, 3, 3, 3, 2};
int n = arr.length;
findMajority(arr, n);
}
}
// This code is contributed by Prajwal Kandekar
Python3
# Function to count the occurrences
def count_occurrences(arr, num):
count = 0
for i in arr:
if i == num:
count += 1
return count
# Function to find the majority element using recursion
def find_majority_util(arr, low, high):
# Base case: single element array
if low == high:
return arr[low]
# Divide the array into left and right halves
mid = (low + high) // 2
left_majority = find_majority_util(arr, low, mid)
right_majority = find_majority_util(arr, mid+1, high)
# If left and right halves have the same majority element
if left_majority == right_majority:
return left_majority
# Count the occurrences of the majority element in the entire array
left_count = count_occurrences(arr[low:high+1], left_majority)
right_count = count_occurrences(arr[low:high+1], right_majority)
# Return the element that occurs more than n/2 times
if left_count > (high-low+1) // 2:
return left_majority
if right_count > (high-low+1) // 2:
return right_majority
# No majority element
return -1
# Function to find the majority element
def find_majority(arr):
n = len(arr)
majority = find_majority_util(arr, 0, n-1)
if majority != -1:
print(majority)
else:
print("No Majority Element")
# Driver Code
if __name__ == "__main__":
arr = [1, 3, 3, 3, 2]
n = len(arr)
find_majority(arr)
# This code is contributed by rambabuguphka
C#
using System;
class Program
{
// Function to count the occurrences
static int CountOccurrences(int[] arr, int num)
{
int count = 0;
foreach (int element in arr)
{
if (element == num)
count++;
}
return count;
}
// Function to find the majority element using recursion
static int FindMajorityUtil(int[] arr, int low, int high)
{
// Base case: single element array
if (low == high)
return arr[low];
// Divide the array into left and right halves
int mid = (low + high) / 2;
int leftMajority = FindMajorityUtil(arr, low, mid);
int rightMajority = FindMajorityUtil(arr, mid + 1, high);
// If left and right halves have the same majority element
if (leftMajority == rightMajority)
return leftMajority;
// Count the occurrences of the majority element in the entire array
int leftCount = CountOccurrences(arr, leftMajority);
int rightCount = CountOccurrences(arr, rightMajority);
// Return the element that occurs more than n/2 times
if (leftCount > (high - low + 1) / 2)
return leftMajority;
if (rightCount > (high - low + 1) / 2)
return rightMajority;
// No majority element
return -1;
}
// Function to find the majority element
static void FindMajority(int[] arr)
{
int n = arr.Length;
int majority = FindMajorityUtil(arr, 0, n - 1);
if (majority != -1)
Console.WriteLine(majority);
else
Console.WriteLine("No Majority Element");
}
// Driver Code
static void Main(string[] args)
{
int[] arr = { 1, 3, 3, 3, 2 };
FindMajority(arr);
// Output will be either the majority element or "No Majority Element"
}
}
Javascript
// JS program for the above approach
// Function to count the occurrences
function countOccurrences(arr, n, num) {
let count = 0;
for (let i = 0; i < n; i++) {
if (arr[i] == num)
count++;
}
return count;
}
// Function to find the majority element
// using recursion
function findMajorityUtil( arr, low, high) {
// Base case: single element array
if (low == high)
return arr[low];
// Divide the array into left
// and right halves
let mid = Math.floor((low + high) / 2);
let leftMajority = findMajorityUtil(arr, low, mid);
let rightMajority = findMajorityUtil(arr, mid+1, high);
// If left and right halves have the
// same majority element
if (leftMajority == rightMajority)
return leftMajority;
// Count the occurrences of the
// majority element in entire array
let leftCount = countOccurrences(arr, high-low+1, leftMajority);
let rightCount = countOccurrences(arr, high-low+1, rightMajority);
// Return the element that occurs
// more than n/2 times
if (leftCount > Math.floor((high-low+1) / 2))
return leftMajority;
if (rightCount > Math.floor((high-low+1) / 2))
return rightMajority;
// No majority element
return -1;
}
// Function to find the majority element
function findMajority(arr, n) {
let majority = findMajorityUtil(arr, 0, n-1);
if (majority != -1)
document.write(majority);
else
document.write("No Majority Element");
}
// Driver Code
let arr = [1, 3, 3, 3, 2];
let n = arr.length;
findMajority(arr, n);
Time Complexity: O(N*log N)
Space Complexity: O(log N)
Majority Element Using Bit Manipulation:
In this approach, we utilize bitwise operations to count the occurrences of each bit position for all elements in the array. By analyzing the majority bits obtained, we can reconstruct the majority element.
Illustration:
Consider an array arr[] = {3, 4, 3, 2, 4, 4, 4, 4} with n = 8.
Iterate through each element in the array and count the occurrences of each bit position.
Reconstruct the majority element from the majority bits obtained.
Check if the reconstructed majority element appears more than n/2 times in the array.
Follow the steps below to solve the given problem:
- Iterate through the array and count the occurrences of each bit position using bitwise operations.
- Reconstruct the majority element from the majority bits obtained.
- Check if the reconstructed majority element appears more than n/2 times in the array.
Below is the implementation of the above idea:
C++
#include <iostream>
#include <vector>
using namespace std;
int majorityElement(vector<int>& nums) {
int num_bits = 32;
int majority_element = 0;
for (int i = 0; i < num_bits; ++i) {
int count_ones = 0, count_zeros = 0;
for (int num : nums) {
if ((num >> i) & 1)
count_ones++;
else
count_zeros++;
}
if (count_ones > count_zeros)
majority_element |= (1 << i);
}
int count_majority = 0;
for (int num : nums) {
if (num == majority_element)
count_majority++;
}
return count_majority > nums.size() / 2 ? majority_element : -1;
}
int main() {
vector<int> nums = {3, 3, 4, 2, 4, 4, 2, 4, 4};
int result = majorityElement(nums);
if (result != -1)
cout << "Majority Element: " << result << endl;
else
cout << "No Majority Element" << endl;
return 0;
}
C
#include <stdio.h>
int majorityElement(int nums[], int numsSize) {
int numBits = sizeof(int) * 8;
int majorityElement = 0;
for (int i = 0; i < numBits; i++) {
int countOnes = 0, countZeros = 0;
for (int j = 0; j < numsSize; j++) {
if ((nums[j] >> i) & 1)
countOnes++;
else
countZeros++;
}
if (countOnes > countZeros)
majorityElement |= (1 << i);
}
int countMajority = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] == majorityElement)
countMajority++;
}
return countMajority > numsSize / 2 ? majorityElement : -1;
}
int main() {
int nums[] = {3, 3, 4, 2, 4, 4, 2, 4, 4};
int numsSize = sizeof(nums) / sizeof(nums[0]);
int result = majorityElement(nums, numsSize);
if (result != -1)
printf("Majority Element: %d\n", result);
else
printf("No Majority Element\n");
return 0;
}
Java
import java.util.*;
public class MajorityElement {
public static int majorityElement(int[] nums) {
int numBits = 32;
int majorityElement = 0;
for (int i = 0; i < numBits; i++) {
int countOnes = 0, countZeros = 0;
for (int num : nums) {
if (((num >> i) & 1) == 1)
countOnes++;
else
countZeros++;
}
if (countOnes > countZeros)
majorityElement |= (1 << i);
}
int countMajority = 0;
for (int num : nums) {
if (num == majorityElement)
countMajority++;
}
return countMajority > nums.length / 2 ? majorityElement : -1;
}
public static void main(String[] args) {
int[] nums = {3, 3, 4, 2, 4, 4, 2, 4, 4};
int result = majorityElement(nums);
if (result != -1)
System.out.println("Majority Element: " + result);
else
System.out.println("No Majority Element");
}
}
Python
def majorityElement(nums):
num_bits = 32
majority_element = 0
for i in range(num_bits):
count_ones = 0
count_zeros = 0
for num in nums:
if (num >> i) & 1:
count_ones += 1
else:
count_zeros += 1
if count_ones > count_zeros:
majority_element |= (1 << i)
count_majority = 0
for num in nums:
if num == majority_element:
count_majority += 1
return majority_element if count_majority > len(nums) // 2 else -1
nums = [3, 3, 4, 2, 4, 4, 2, 4, 4]
result = majorityElement(nums)
if result != -1:
print("Majority Element:", result)
else:
print("No Majority Element")
C#
using System;
using System.Collections.Generic;
public class Program {
public static int MajorityElement(int[] nums) {
int numBits = 32;
int majorityElement = 0;
for (int i = 0; i < numBits; i++) {
int countOnes = 0, countZeros = 0;
foreach (int num in nums) {
if (((num >> i) & 1) == 1)
countOnes++;
else
countZeros++;
}
if (countOnes > countZeros)
majorityElement |= (1 << i);
}
int countMajority = 0;
foreach (int num in nums) {
if (num == majorityElement)
countMajority++;
}
return countMajority > nums.Length / 2 ? majorityElement : -1;
}
public static void Main() {
int[] nums = {3, 3, 4, 2, 4, 4, 2, 4, 4};
int result = MajorityElement(nums);
if (result != -1)
Console.WriteLine("Majority Element: " + result);
else
Console.WriteLine("No Majority Element");
}
}
JavaScript
function majorityElement(nums) {
const numBits = 32;
let majorityElement = 0;
for (let i = 0; i < numBits; i++) {
let countOnes = 0, countZeros = 0;
for (let num of nums) {
if ((num >> i) & 1)
countOnes++;
else
countZeros++;
}
if (countOnes > countZeros)
majorityElement |= (1 << i);
}
let countMajority = 0;
for (let num of nums) {
if (num === majorityElement)
countMajority++;
}
return countMajority > nums.length / 2 ? majorityElement : -1;
}
const nums = [3, 3, 4, 2, 4, 4, 2, 4, 4];
const result = majorityElement(nums);
if (result !== -1)
console.log("Majority Element:", result);
else
console.log("No Majority Element");
Output:
Majority Element: 4
Time Complexity: O(n * k), where n is the number of elements in the array and k is the number of bits in an integer.
Auxiliary Space: O(1), As no extra space is required.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...