Open In App

Majority Element

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given an array arr, and your task is to find the majority element an element that occurs more than half the length of the array (i.e., arr.size() / 2). If such an element exists return it, otherwise return -1, indicating that no majority element is present.

Examples : 

Input : arr[] = [1, 1, 2, 1, 3, 5, 1]
Output : 1
Explanation: Since, 1 appear 4 times which is more than 7 / 2 times 

Input: arr[] = [7]
Output: 7
Explanation: Since, 7 is single element and present more than 1/2 times, so it is the majority element.

Input: arr[] = [2, 13]
Output: -1
Explanation: Since, no element is present more than 2/2 times, so there is no majority element.

[Naive Approach] Using Two Nested Loops - O(n^2) Time and O(1) Space

The idea is to count the frequency of each element using nested loops.

  • The first loop iterates through each element of the array, treating it as a the majority element.
  • For each element, the second loop counts its occurrences in the entire array.
  • After the second loop, we check if this element appears more than n / 2 times, where nis the size of the array.
  • If it does, it is the majority element in the array.
C++
// C++ program to find Majority
// element in an array using nested loops

#include <bits/stdc++.h>
using namespace std;

// Function to find the Majority element in an array
int majorityElement(vector<int>& arr) {
    int n = arr.size();  

    // Loop to consider each element as a candidate for majority
    for (int i = 0; i < n; i++) {
        int count = 0; 

        // Inner loop to count the frequency of arr[i]
        for (int j = 0; j < n; j++) {
            if (arr[i] == arr[j]) {
                count++;
            }
        }

        // Check if count of arr[i] is more than half the size of the array
        if (count > n / 2) {
            return arr[i]; 
        }
    }

    // If no majority element found, return -1
    return -1;
}

int main() {
    vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
    
    cout << majorityElement(arr) << endl;

    return 0;
}
C
// C program to find Majority
// element in an array using nested loops

#include <stdio.h>

// Function to find the Majority element in an array
int majorityElement(int arr[], int n) {
    // Loop to consider each element as a candidate for majority
    for (int i = 0; i < n; i++) {
        int count = 0; 

        // Inner loop to count the frequency of arr[i]
        for (int j = 0; j < n; j++) {
            if (arr[i] == arr[j]) {
                count++;
            }
        }

        // Check if count of arr[i] is more than half the size of the array
        if (count > n / 2) {
            return arr[i]; 
        }
    }

    // If no majority element found, return -1
    return -1;
}

int main() {
    int arr[] = {1, 1, 2, 1, 3, 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("%d\n", majorityElement(arr, n));

    return 0;
}
Java
// Java program to find Majority
// element in an array using nested loops

import java.util.*;

class GfG {

    // Function to find the Majority element in an array
    static int majorityElement(int[] arr) {
        int n = arr.length; 

        // Loop to consider each element as a candidate for majority
        for (int i = 0; i < n; i++) {
            int count = 0;

            // Inner loop to count the frequency of arr[i]
            for (int j = 0; j < n; j++) {
                if (arr[i] == arr[j]) {
                    count++;
                }
            }

            // Check if count of arr[i] is more than half the size of the array
            if (count > n / 2) {
                return arr[i];
            }
        }

        // If no majority element found, return -1
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 1, 3, 5, 1};

        System.out.println(majorityElement(arr));
    }
}
Python
# Python3 program to find Majority
# element in an array using nested loops

# Function to find the Majority element in an array
def majorityElement(arr):
    n = len(arr)  

    # Loop to consider each element as a candidate for majority
    for i in range(n):
        count = 0

        # Inner loop to count the frequency of arr[i]
        for j in range(n):
            if arr[i] == arr[j]:
                count += 1

        # Check if count of arr[i] is more than half the size of the array
        if count > n // 2:
            return arr[i]

    # If no majority element found, return -1
    return -1

if __name__ == "__main__":
	arr = [1, 1, 2, 1, 3, 5, 1]
	print(majorityElement(arr))
C#
// C# program to find Majority
// element in an array using nested loops

using System;

class GfG {

    // Function to find the Majority element in an array
    static int majorityElement(int[] arr) {
        int n = arr.Length; 

        // Loop to consider each element as a candidate for majority
        for (int i = 0; i < n; i++) {
            int count = 0;

            // Inner loop to count the frequency of arr[i]
            for (int j = 0; j < n; j++) {
                if (arr[i] == arr[j]) {
                    count++;
                }
            }

            // Check if count of arr[i] is more than half the size of the array
            if (count > n / 2) {
                return arr[i];
            }
        }

        // If no majority element found, return -1
        return -1;
    }

    static void Main(string[] args) {
        int[] arr = { 1, 1, 2, 1, 3, 5, 1 };
        Console.WriteLine(majorityElement(arr));
    }
}
Javascript
// Javascript program to find Majority
// element in an array using nested loops

// Function to find the Majority element in an array
function majorityElement(arr) {
    let n = arr.length;  

    // Loop to consider each element as a candidate for majority
    for (let i = 0; i < n; i++) {
        let count = 0;

        // Inner loop to count the frequency of arr[i]
        for (let j = 0; j < n; j++) {
            if (arr[i] === arr[j]) {
                count++;
            }
        }

        // Check if count of arr[i] is more than half the size of the array
        if (count > n / 2) {
            return arr[i];
        }
    }

    // If no majority element found, return -1
    return -1;
}

// Driver Code 
let arr = [1, 1, 2, 1, 3, 5, 1];
console.log(majorityElement(arr));

Output
1

[Better Approach 1] Using Sorting - O(n log n) Time and O(1) Space

The idea is to sort the array so that similar elements are next to each other. Once sorted, go through the array and keep track of how many times each element appears. When you encounter a new element, check if the count of the previous element was more than half the total number of elements in the array. If it was, that element is the majority and should be returned. If no element meets this requirement, no majority element exists.

C++
// C++ program to find Majority
// element in an array using sorting
#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();
    sort(arr.begin(), arr.end());
    
    // potential majority element
    int candidate = arr[n/2];  

    // Count how many times candidate appears
    int count = 0;
    for (int num : arr) {
        if (num == candidate) {
            count++;
        }
    }

    if (count > n/2) {
        return candidate;
    }
    
    // No majority element
    return -1;  
}


int main() {
    vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
  
    cout << majorityElement(arr);

    return 0;
}
Java
// Java program to find Majority
// element in an array using sorting

import java.util.Arrays;

class GfG {
  
    // Function to find Majority element in an array
    // it returns -1 if there is no majority element
    static int majorityElement(int[] arr) {
        int n = arr.length;
        Arrays.sort(arr);
        // Potential majority element
        int candidate = arr[n/2];  
    
        int count = 0;
        for (int num : arr) {
            if (num == candidate) {
                count++;
            }
        }
    
        if (count > n/2) {
            return candidate;
        }
        // No majority element
        return -1;  
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 1, 3, 5, 1};
        System.out.println(majorityElement(arr));
    }
}
Python
# Function to find Majority element in an array
# It returns -1 if there is no majority element
def majorityElement(arr):
    n = len(arr)
    arr.sort()
    
    candidate = arr[n // 2]

    count = 0
    for num in arr:
        if num == candidate:
            count += 1
    
    if count > n // 2:
        return candidate
    else:
        return -1


if __name__ == "__main__":
    arr = [1, 1, 2, 1, 3, 5, 1]
    print(majorityElement(arr))
C#
// C# program to find Majority
// element in an array using sorting
using System;

class GfG {
  
    // Function to find Majority element in an array
    // it returns -1 if there is no majority element
    static int MajorityElement(int[] arr) {
        int n = arr.Length;
        Array.Sort(arr);
    
        int candidate = arr[n / 2];
    
        int count = 0;
        foreach (int num in arr) {
            if (num == candidate) {
                count++;
            }
        }
    
        if (count > n / 2) {
            return candidate;
        } else {
            return -1;
        }
    }

    static void Main() {
        int[] arr = {1, 1, 2, 1, 3, 5, 1};
        Console.WriteLine(MajorityElement(arr));
    }
}
Javascript
// Function to find Majority element in an array
// it returns -1 if there is no majority element
function majorityElement(arr) {
    let n = arr.length;
    arr.sort((a, b) => a - b);

    let candidate = arr[Math.floor(n / 2)];

    let count = 0;
    for (let num of arr) {
        if (num === candidate) {
            count++;
        }
    }

    if (count > Math.floor(n / 2)) {
        return candidate;
    } else {
        return -1;
    }
}


// Driver Code 
let arr = [1, 1, 2, 1, 3, 5, 1];
console.log(majorityElement(arr));

Output
1

[Better Approach 2] Using Hashing - O(n) Time and O(n) Space

The idea is to use a hash map to count the occurrences of each element in the array.

  • Traverse the array once, and for each element, update its count in the hash map.
  • After updating the count, check if count exceeds n / 2.
  • If such an element is found, return it immediately.
  • If no element's count exceeds n / 2, return-1.
C++
// C++ program to find Majority
// element in an array using hashmap

#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(const vector<int> &arr) {
    int n = arr.size();
    unordered_map<int, int> countMap;

    // Traverse the array and count occurrences using the hash map
    for (int num : arr) {
        countMap[num]++;

        // Check if current element count exceeds n / 2
        if (countMap[num] > n / 2) {
            return num;
        }
    }

    // If no majority element is found, return -1
    return -1;
}

int main() {
    vector<int> arr = {1, 1, 2, 1, 3, 5, 1};

    cout << majorityElement(arr) << endl;

    return 0;
}
Java
// Java program to find Majority
// element in an array using hashmap

import java.util.HashMap;
import java.util.Map;

class GfG {
    
    // Function to find Majority element in an array
    // It returns -1 if there is no majority element
    static int majorityElement(int[] arr) {
        int n = arr.length;
        Map<Integer, Integer> countMap = new HashMap<>();

        // Traverse the array and count occurrences using the hash map
        for (int num : arr) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
          
            // Check if current element count exceeds n / 2
            if (countMap.get(num) > n / 2) {
                return num;
            }
        }

        // If no majority element is found, return -1
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 1, 3, 5, 1};
        System.out.println(majorityElement(arr));
    }
}
Python
# Python program to find Majority
# element in an array using hashmap
from collections import defaultdict

# Function to find Majority element in a list
# It returns -1 if there is no majority element
def majorityElement(arr):
    n = len(arr)
    countMap = defaultdict(int)

    # Traverse the list and count occurrences using the hash map
    for num in arr:
        countMap[num] += 1
        
        # Check if current element count exceeds n / 2
        if countMap[num] > n / 2:
            return num

    # If no majority element is found, return -1
    return -1

if __name__ == "__main__":
	arr = [1, 1, 2, 1, 3, 5, 1]
	print(majorityElement(arr))
C#
// C# program to find Majority
// element in an array using hashmap

using System;
using System.Collections.Generic;

class GfG {
  
    // Function to find Majority element in an array
    // It returns -1 if there is no majority element
    static int majorityElement(int[] arr) {
        int n = arr.Length;
        Dictionary<int, int> countMap = new Dictionary<int, int>();

        // Traverse the array and count occurrences using the hash map
        foreach (int num in arr) {
            if (countMap.ContainsKey(num))
                countMap[num]++;
            else
                countMap[num] = 1;

            // Check if current element count exceeds n / 2
            if (countMap[num] > n / 2) {
                return num;
            }
        }

        // If no majority element is found, return -1
        return -1;
    }

    public static void Main() {
        int[] arr = {1, 1, 2, 1, 3, 5, 1};
        Console.WriteLine(majorityElement(arr));
    }
}
Javascript
// Javascript program to find Majority
// element in an array using hashmap

// Function to find Majority element in an array
// It returns -1 if there is no majority element
function majorityElement(arr) {
    const n = arr.length;
    const countMap = new Map();

    // Traverse the array and count occurrences using the hash map
    for (const num of arr) {
        countMap.set(num, (countMap.get(num) || 0) + 1);
        
        // Check if current element count exceeds n / 2
        if (countMap.get(num) > n / 2) {
            return num;
        }
    }

    // If no majority element is found, return -1
    return -1;
}

// Driver Code
const arr = [1, 1, 2, 1, 3, 5, 1];
console.log(majorityElement(arr));

Output
1

[Expected Approach] Using Moore's Voting Algorithm- O(n) Time and O(1) Space

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:

  • Initialize a candidatevariable and a countvariable.
  • Traverse the array once:
    • If countis zero, set the candidateto the current element and set countto one.
    • If the current element equals the candidate, increment count.
    • If the current element differs from the candidate, decrement count.
  • Traverse the array again to count the occurrences of the candidate.
  • If the candidate's count is greater than n / 2, return the candidate as the majority element.
C++
// C++ program to find Majority
// element in an array

#include <bits/stdc++.h>
using namespace std;

// Function to find the Majority element in an array using Boyer-Moore Voting Algorithm
// It returns -1 if there is no majority element
int majorityElement(const vector<int>& arr) {
    int n = arr.size();
    int candidate = -1;
    int count = 0;

    // Find a candidate
    for (int num : arr) {
        if (count == 0) {
            candidate = num;
            count = 1;
        } else if (num == candidate) {
            count++;
        } else {
            count--;
        }
    }

    // Validate the candidate
    count = 0;
    for (int num : arr) {
        if (num == candidate) {
            count++;
        }
    }

    // If count is greater than n / 2, return the candidate; otherwise, return -1
    if (count > n / 2) {
        return candidate;
    } else {
        return -1;
    }
}

int main() {
    vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
    cout << majorityElement(arr) << endl;
    return 0;
}
C
// C program to find Majority
// element in an array

#include <stdio.h>

int majorityElement(int arr[], int n) {
    int candidate = -1;
    int count = 0;

    // Find a candidate
    for (int i = 0; i < n; i++) {
        if (count == 0) {
            candidate = arr[i];
            count = 1;
        } else if (arr[i] == candidate) {
            count++;
        } else {
            count--;
        }
    }

    // Validate the candidate
    count = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == candidate) {
            count++;
        }
    }

  	// If count is greater than n / 2, return the candidate; otherwise, return -1
    if (count > n / 2) {
        return candidate;
    } else {
        return -1;
    }
}

int main() {
    int arr[] = {1, 1, 2, 1, 3, 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", majorityElement(arr, n));
    return 0;
}
Java
// Java program to find Majority
// element in an array

class GfG {
    static int majorityElement(int[] arr) {
        int n = arr.length;
        int candidate = -1;
        int count = 0;

        // Find a candidate
        for (int num : arr) {
            if (count == 0) {
                candidate = num;
                count = 1;
            } else if (num == candidate) {
                count++;
            } else {
                count--;
            }
        }

        // Validate the candidate
        count = 0;
        for (int num : arr) {
            if (num == candidate) {
                count++;
            }
        }
	
      	// If count is greater than n / 2, return the candidate; otherwise, return -1
        if (count > n / 2) {
            return candidate;
        } else {
            return -1;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 1, 3, 5, 1};
        System.out.println(majorityElement(arr));
    }
}
Python
# Python program to find Majority
# element in an array

def majorityElement(arr):
    n = len(arr)
    candidate = -1
    count = 0

    # Find a candidate
    for num in arr:
        if count == 0:
            candidate = num
            count = 1
        elif num == candidate:
            count += 1
        else:
            count -= 1

    # Validate the candidate
    count = 0
    for num in arr:
        if num == candidate:
            count += 1

    # If count is greater than n / 2, return the candidate; otherwise, return -1
    if count > n // 2:
        return candidate
    else:
        return -1

if __name__ == "__main__":
    arr = [1, 1, 2, 1, 3, 5, 1]
    print(majorityElement(arr))
C#
// C# program to find Majority
// element in an array

using System;

class GfG {
     static int majorityElement(int[] arr) {
        int n = arr.Length;
        int candidate = -1;
        int count = 0;

        // Find a candidate
        foreach (int num in arr) {
            if (count == 0) {
                candidate = num;
                count = 1;
            } else if (num == candidate) {
                count++;
            } else {
                count--;
            }
        }

        // Validate the candidate
        count = 0;
        foreach (int num in arr) {
            if (num == candidate) {
                count++;
            }
        }
	
      	// If count is greater than n / 2, return the candidate; otherwise, return -1
        if (count > n / 2) {
            return candidate;
        } else {
            return -1;
        }
    }

    static void Main() {
        int[] arr = {1, 1, 2, 1, 3, 5, 1};
        Console.WriteLine(majorityElement(arr));
    }
}
Javascript
// JavaScript program to find Majority
// element in an array

function majorityElement(arr) {
    const n = arr.length;
    let candidate = -1;
    let count = 0;

    // Find a candidate
    for (const num of arr) {
        if (count === 0) {
            candidate = num;
            count = 1;
        } else if (num === candidate) {
            count++;
        } else {
            count--;
        }
    }

    // Validate the candidate
    count = 0;
    for (const num of arr) {
        if (num === candidate) {
            count++;
        }
    }
	
    // If count is greater than n / 2, return the candidate; otherwise, return -1
    if (count > n / 2) {
        return candidate;
    } else {
        return -1;
    }
}

// Driver Code 
const arr = [1, 1, 2, 1, 3, 5, 1];
console.log(majorityElement(arr));

Output
1

Next Article

Similar Reads