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

Majority Element

Last Updated : 25 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given an array arr. Find the majority element in the array. If no majority exists, return -1. A majority element in an array is an element that appears strictly more than arr.size() / 2 times in the array.

Examples : 

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

Input : arr[] = [3, 3, 4, 2, 4, 4, 2, 4]
Output : -1
Explanation: There is no element whose frequency is greater than the half of the size of the array size.

Input : arr[] = [3]
Output : 3
Explanation: Appears more than n/2 times

[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 n is the size of the array.
  • If it does, it is the majority element in the array.

Below is the implementation of the above approach:

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(const 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;
}

let arr = [1, 1, 2, 1, 3, 5, 1];

console.log(majorityElement(arr));

Output
1

[Better Approach] 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.

Below is the implementation of the above approach: 

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

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

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

#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

// 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(n log n)
    qsort(arr, n, sizeof(int), compare);

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

int main() {
    int arr[] = {1, 1, 2, 1, 3, 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("%d", majorityElement(arr, n));

    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;
        if (n == 1) return arr[0];

        int cnt = 1;
        Arrays.sort(arr); 

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

    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 sorting

# Function to find Majority element in an array
# it returns -1 if there is no majority element
def majorityElement(arr):
    n = len(arr)
    if n == 1:
        return arr[0]
    
    cnt = 1
    arr.sort()
    
    for i in range(1, n):
        if arr[i - 1] == arr[i]:
            cnt += 1
        else:
            if cnt > n // 2:
                return arr[i - 1]
            cnt = 1
    
    # Check the last element
    if cnt > n // 2:
        return arr[-1]
    
    # if no majority element, return -1
    return -1

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;
        if (n == 1) return arr[0];
        
        int cnt = 1;
        Array.Sort(arr); 

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

    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 sorting

// Function to find Majority element in an array
// it returns -1 if there is no majority element
function majorityElement(arr) {
    let n = arr.length;
    if (n === 1) return arr[0];

    let cnt = 1;
    arr.sort((a, b) => a - b); 

    for (let i = 1; i < n; i++) {
        if (arr[i - 1] === arr[i]) {
            cnt++;
        } else {
            if (cnt > Math.floor(n / 2)) {
                return arr[i - 1];
            }
            cnt = 1;
        }
    }

    // Check the last element
    if (cnt > Math.floor(n / 2)) {
        return arr[n - 1];
    }

    // if no majority element, return -1
    return -1;
}

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

Output
1

[Optimal Approach] 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.

Below is the implementation of the above approach:

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 majority_element(arr):
    n = len(arr)
    count_map = defaultdict(int)

    # Traverse the list and count occurrences using the hash map
    for num in arr:
        count_map[num] += 1
        
        # Check if current element count exceeds n / 2
        if count_map[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(majority_element(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;
}

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 candidate variable and a count variable.
  • Traverse the array once:
    • If count is zero, set the candidate to the current element and set count to 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.

Below is the implementation of the above approach: 

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 majority_element(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(majority_element(arr))
C#
// C# program to find Majority
// element in an array

using System;

class GfG {
    public static int FindMajorityElement(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(FindMajorityElement(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;
    }
}

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

Output
1


Next Article

Similar Reads

three90RightbarBannerImg