The Wayback Machine - https://web.archive.org/web/20240818163938/https://www.geeksforgeeks.org/majority-element/
Open In App

Majority Element

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Output
1

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.

Using Moore’s Voting Algorithm (The Best Approach)

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
?>

Output
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.

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);

Output
Majority 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.

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));

Output
1

Time Complexity: O(n log n), Sorting requires O(n log n) time complexity.
Auxiliary Space: O(1), As no extra space is required.



Previous Article
Next Article

Similar Reads

Find majority element using Bit Magic
Pre-requisite: Majority Element, Majority Element | Set-2 (Hashing)Given an array of size N, find the majority element. The majority element is the element that appears more than n/2 times in the given array. Examples: Input: {3, 3, 4, 2, 4, 4, 2, 4, 4} Output: 4 Input: {3, 3, 6, 2, 4, 4, 2, 4} Output: No Majority Element Approach:In this post, we
8 min read
Check if an array has a majority element
Given an array, the task is to find if the input array contains a majority element or not. An element is Examples: Input : arr[] = {2, 3, 9, 2, 2} Output : Yes A majority element 2 is present in arr[] Input : arr[] = {1, 8, 9, 2, 5} Output : No A simple solution is to traverse through the array. For every element, count its occurrences. If the coun
4 min read
Majority element in a linked list
Given a linked list, find majority element. An element is called Majority element if it appears more than or equal to n/2 times where n is total number of nodes in the linked list. Examples: Input : 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;1-&gt;1-&gt;1-&gt;NULL Output : 1 Explanation 1 occurs 4 times Input :10-&gt;23-&gt;11-&gt;9-&gt;54-&gt;NULL Output :NO m
14 min read
Count majority element in a matrix
Given a NxM matrix of integers containing duplicate elements. The task is to find the count of all majority occurring elements in the given matrix, where majority element are those whose frequency is greater than or equal to (N*M)/2. Examples: Input : mat[] = {{1, 1, 2}, {2, 3, 3}, {4, 3, 3}} Output : 1 The majority elements is 3 and, its frequency
6 min read
Majority element in a circular array of 0's and 1's
Given a circular array containing only 0’s and 1’s, of size n where n = p*q (p and q are both odd integers). The task is to check if there is a way such that 1 will be in majority after applying the following operations: Divide circular array into p subarrays each of size q.In each subarray, the number which is in majority will get stored into arra
15+ min read
Minimum length of subarray in given Ternary Array having 0 as the majority element
Given an integer array arr[] of size n with only three types of integers 0's, 1's, and 2's. Find the minimum length of the subarray of the array arr[] of length &gt;=2, such that it has a frequency of 0's greater than both 1's and 2's. If not found print -1. Input: arr[] = {2, 0, 2, 0, 1, 2, 2, 2}Output : 3Explanation: {0, 2, 0} from index [2, 4] i
13 min read
Minimum swaps of same indexed elements required to obtain a Majority Element in one of the arrays
Given two arrays arr[] and brr[] of length N, the task is to find the minimum number of swaps of the same indexed elements required such an element occurs at least half of the indices in the array arr[], i.e. Majority element. If it is not possible to obtain such an arrangement, then print "-1". Examples: Input: arr[] = {3, 2, 1, 4, 9}, brr[] = {5,
10 min read
Python3 Program for Check for Majority Element in a sorted array
Question: Write a function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 times). Examples:
7 min read
Javascript Program to Check Majority Element in a sorted array
Question: Write a function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 times). Examples:
3 min read
Check for Majority Element in a sorted array
Given an array arr of N elements, A majority element in an array arr of size N is an element that appears more than N/2 times in the array. The task is to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 t
15+ min read
Maximum count of Strings to be selected such that there is a majority character
Given an array A[]of N strings of lowercase characters, the task is to find maximum number of strings, such that one character has majority i.e. the occurrence of one character in all of the strings is greater than all the other characters combined. Examples: Input: A[] = {"aba", "abcde", "aba"}Output: 2Explanation: On choosing {"aba", "aba"}, the
11 min read
Minimize range [L, R] to divide Array into K subarrays with majority elements in [L, R]
Given an array arr[] of size N, the task is to find the minimum value range [L, R] such that: The array can be divided into K sub-arrays.The elements within the range [L, R] are greater than the elements which are out of the range[l, r]. Examples: Input: arr[] = {1, 2, 2, 2}, K = 2Output: 2 2Explanation: [2, 2] is the range with minimum distance wh
12 min read
Boyer-Moore Majority Voting Algorithm for Searching elements having more than K Occurrences
The Boyer-Moore Majority Voting Algorithm is a well-known and efficient algorithm used to find the majority element in an array, i.e., an element that appears more than n/2 times. This algorithm, initially designed by Robert S. Boyer and J Strother Moore in 1981, is widely used in various applications, including data analysis and stream processing.
9 min read
Boyer-Moore Majority Voting Algorithm
The Boyer-Moore voting algorithm is one of the popular optimal algorithms which is used to find the majority element among the given elements that have more than N/ 2 occurrences. This works perfectly fine for finding the majority element which takes 2 traversals over the given elements, which works in O(N) time complexity and O(1) space complexity
7 min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Largest element smaller than current element on left for every element in Array
Given an array arr[] of the positive integers of size N, the task is to find the largest element on the left side of each index which is smaller than the element present at that index. Note: If no such element is found then print -1. Examples: Input: arr[] = {2, 5, 10} Output: -1 2 5 Explanation : Index 0: There are no elements before it So Print -
11 min read
Closest greater element for every array element from another array
Given two arrays a[] and b[], we need to build an array c[] such that every element c[i] of c[] contains a value from a[] which is greater than b[i] and is closest to b[i]. If a[] has no greater element than b[i], then value of c[i] is -1. All arrays are of same size. Examples: Input : a[] = [ 2, 6, 5, 7, 0] b[] = [1, 3, 2, 5, 8] Output : c[] = [2,
5 min read
Range Query on array whose each element is XOR of index value and previous element
Consider an arr[] which can be defined as: You are given Q queries of the form [l, r]. The task is to output the value of arr[l] ? arr[l+1] ? ..... ? arr[r-1] ? arr[r] for each query. Examples : Input : q = 3 q1 = { 2, 4 } q2 = { 2, 8 } q3 = { 5, 9 } Output : 7 9 15 The beginning of the array with constraint look like: arr[] = { 0, 1, 3, 0, 4, 1, 7
9 min read
Find last element after deleting every second element in array of n integers
Given a circular array of size n containing integers from 1 to n. Find the last element that would remain in the list after erasing every second element starting from the first element. Example: Input: 5 Output: 3 Explanation Element in circular array are: 1 2 3 4 5 Starting from first element i.e, '1' delete every second element like this, 1 0 3 4
7 min read
Sum of product of each element with each element after it
Given an array arr[] of n integers. The task is to find the sum of product of each element with each element after it in the array. In other words, find sum of product of each arr[i] with each arr[j] such that j &gt; i. Examples : Input : arr[] = {9, 3, 4, 2}Output : 107Explanation: Sum of product of arr[0] with arr[1], arr[2], arr[3] is 9*3 + 9*4
10 min read
Find last element of Array by rotating and deleting N-K+1 element
Given an array arr[] of N integers, the task is to find the element which is left at last after performing the following operation N - 1 time. For every Kth operation: Right-rotate the array clockwise by 1.Delete the (n - K + 1)th last element. Example: Input: N = 6, arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Rotate the array clockwise i.e. af
7 min read
Replace every element with the greatest element on its left side
Given an array of integers, the task is to replace every element with the greatest element on its left side. Note: Replace the first element with -1 as it has no element in its left. Examples: Input: arr[] = {4, 5, 2, 1, 7, 6}Output: -1 4 5 5 5 7Explanation:Since, 4 has no element in its left, so replace it by -1.For 5, 4 is the greatest element in
6 min read
Longest Subarray with first element greater than or equal to Last element
Given an array arr[0..n-1] of n integers, find the maximum length subarray such that its first element is greater than or equal to the last element of the subarray. Examples: Input : arr[] = {-5, -1, 7, 5, 1, -2} Output : 5 Explanation : Subarray {-1, 7, 5, 1, -2} forms maximum length subarray with its first element greater than last. Input : arr[]
12 min read
Replace every array element by Bitwise Xor of previous and next element
Given an array of integers, replace every element with xor of previous and next elements with following exceptions. First element is replaced by xor of first and second. Last element is replaced by xor of last and second last. Examples: Input: arr[] = { 2, 3, 4, 5, 6}Output: 1 6 6 2 3 We get the following array as {2^3, 2^4, 3^5, 4^6, 5^6} Input: a
10 min read
Replace every element with the smallest element on its left side
Given an array of integers, the task is to replace every element with the smallest element on its left side. Note: Replace the first element with -1 as it has no element in its left. Examples: Input: arr[] = {4, 5, 2, 1, 7, 6} Output: -1 4 4 2 1 1 Since, 4 has no element in its left, so replace it by -1. For 5, 4 is the smallest element in its left
7 min read
Sum of (maximum element - minimum element) for all the subsets of an array.
Given an array arr[], the task is to compute the sum of (max{A} - min{A}) for every non-empty subset A of the array arr[].Examples: Input: arr[] = { 4, 7 } Output: 3There are three non-empty subsets: { 4 }, { 7 } and { 4, 7 }. max({4}) - min({4}) = 0 max({7}) - min({7}) = 0 max({4, 7}) - min({4, 7}) = 7 - 4 = 3.Sum = 0 + 0 + 3 = 3Input: arr[] = { 4
10 min read
Maximum sum in an array such that every element has exactly one adjacent element to it
Given an array arr[] of N integers, you can select some indexes such that every selected index has exactly one other selected index adjacent to it and the sum of elements at the chosen indexes should be maximum. In other words, the task is to select elements from an array such that a single element alone is not selected and elements at three consec
9 min read
Maximum element in an array such that its previous and next element product is maximum
Given an array arr[] of N integers, the task is to print the largest element among the array such that its previous and next element product is maximum.Examples: Input: arr[] = {5, 6, 4, 3, 2} Output: 6 The product of the next and the previous elements for every element of the given array are: 5 -&gt; 2 * 6 = 12 6 -&gt; 5 * 4 = 20 4 -&gt; 6 * 3 = 1
6 min read
Replace elements with absolute difference of smallest element on left and largest element on right
Given an array arr[] of N integers. The task is to replace all the elements of the array by the absolute difference of the smallest element on its left and the largest element on its right.Examples: Input: arr[] = {1, 5, 2, 4, 3} Output: 5 3 3 2 1 ElementSmallest on its leftLargest on its rightAbsolute difference1NULL5551432143413231NULL1 Input: ar
15+ min read
Maximum possible remainder when an element is divided by other element in the array
Given an array arr[] of N integers, the task is to find the maximum mod value for any pair (arr[i], arr[j]) from the array.Examples: Input: arr[] = {2, 4, 1, 5, 3, 6} Output: 5 (5 % 6) = 5 is the maximum possible mod value.Input: arr[] = {6, 6, 6, 6} Output: 0 Approach: It is known that when an integer is divided by some other integer X, the remain
4 min read
three90RightbarBannerImg