Open In App

Majority Element II – Elements occurring more than ⌊N/3⌋ times

Last Updated : 23 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of n integers, the task is to find all the array elements which occurs more than floor(n/3) times.
Note: The returned array of majority elements should be sorted.

Examples:

Input: arr[] = {2, 2, 3, 1, 3, 2, 1, 1}
Output: {1, 2}
Explanation: The frequency of 1 and 2 is 3, which is more than floor n/3 (8/3 = 2).

Input: arr[] = {-5, 3, -5}
Output: {-5}
Explanation: The frequency of -5 is 2, which is more than floor n/3 (3/3 = 1).

Input: arr[] = {3, 2, 2, 4, 1, 4}
Output: { }
Explanation: There is no majority element.

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

The idea is to iterate over all elements and count the frequency of the element in the array. If the frequency of the element is greater than floor(n/3), add it to the result. To avoid adding duplicate elements into the result, we can check if the element is already present in the result. We can stop the iteration if we have already found two majority elements.

C++
// C++ program to find Majority elements in an array
// using nested loops

#include <iostream>
#include <vector>
using namespace std;

// Function to find Majority elements in an array
vector<int> findMajority(vector<int> &arr) {
    int n = arr.size();
    vector<int> res;

    for (int i = 0; i < n; i++) {
        
        // Count the frequency of arr[i]
        int cnt = 0;
        for (int j = i; j < n; j++) {
            if (arr[j] == arr[i])
                cnt += 1;
        }
      
        // Check if arr[i] is a majority element
        if (cnt > (n / 3)) {
          
            // Add arr[i] only if it is not already
            // present in the result
            if (res.size() == 0 || arr[i] != res[0]) {
                res.push_back(arr[i]);
            }
        }
      
        // If we have found two majority elements, 
        // we can stop our search
        if (res.size() == 2) {
            if(res[0] > res[1])
                swap(res[0], res[1]);
            break;
        }
    }

    return res;
}

int main() {
    vector<int> arr = {2, 2, 3, 1, 3, 2, 1, 1};
    vector<int> res = findMajority(arr);
    for (int ele : res)
        cout << ele << " ";
    return 0;
}
C
// C program to find Majority element in an array
// using nested loop

#include <stdio.h>

int *findMajority(int *arr, int n, int *resSize) {
    int *res = (int *)malloc(2 * sizeof(int));
    *resSize = 0;

    for (int i = 0; i < n; i++) {
      
        // Count the frequency of arr[i]
        int cnt = 0;
        for (int j = i; j < n; j++) {
            if (arr[j] == arr[i])
                cnt += 1;
        }

        // Check if arr[i] is a majority element
        if (cnt > (n / 3)) {
          
            // Add arr[i] only if it is not already
            // present in the result
            if (*resSize == 0 || arr[i] != res[0]) {
                res[*resSize] = arr[i];
                (*resSize)++;
            }
        }

        // If we have found two majority elements,
        // we can stop our search
        if (*resSize == 2) {
            if (res[0] > res[1]) {
                int temp = res[0];
                res[0] = res[1];
                res[1] = temp;
            }
            break;
        }
    }

    return res;
}

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

    int *res = findMajority(arr, n, &resSize);

    for (int i = 0; i < resSize; i++)
        printf("%d ", res[i]);

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

import java.util.ArrayList;
import java.util.List;

class GfG {
    
    // Function to find Majority elements in an array
    static List<Integer> findMajority(int[] arr) {
        int n = arr.length;
        List<Integer> res = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            
            // Count the frequency of arr[i]
            int cnt = 0;
            for (int j = i; j < n; j++) {
                if (arr[j] == arr[i])
                    cnt += 1;
            }
          
            // Check if arr[i] is a majority element
            if (cnt > (n / 3)) {
              
                // Add arr[i] only if it is not already
                // present in the result
                if (res.size() == 0 || arr[i] != res.get(0)) {
                    res.add(arr[i]);
                }
            }
          
            // If we have found two majority elements, 
            // we can stop our search
            if (res.size() == 2) {
                if (res.get(0) > res.get(1))
                    java.util.Collections.swap(res, 0, 1);
                break;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {2, 2, 3, 1, 3, 2, 1, 1};
        List<Integer> res = findMajority(arr);
        for (int ele : res)
            System.out.print(ele + " ");
    }
}
Python
# Python program to find Majority elements in an array
# using nested loops

def findMajority(arr):
    n = len(arr)
    res = []

    for i in range(n):
        
        # Count the frequency of arr[i]
        cnt = 0
        for j in range(i, n):
            if arr[j] == arr[i]:
                cnt += 1
        
        # Check if arr[i] is a majority element
        if cnt > (n // 3):
            
            # Add arr[i] only if it is not already
            # present in the result
            if len(res) == 0 or arr[i] != res[0]:
                res.append(arr[i])
        
        # If we have found two majority elements, 
        # we can stop our search
        if len(res) == 2:
            if res[0] > res[1]:
                res[0], res[1] = res[1], res[0]
            break

    return res

if __name__ == "__main__":
    arr = [2, 2, 3, 1, 3, 2, 1, 1]
    res = findMajority(arr)
    for ele in res:
        print(ele, end=" ")
C#
// C# program to find Majority element in an array
// using nested loop
using System;
using System.Collections.Generic;

class GfG {
  
    // Function to find Majority elements in an array
    static List<int> findMajority(int[] arr) {
        int n = arr.Length;
        List<int> res = new List<int>();

        for (int i = 0; i < n; i++) {
            
            // Count the frequency of arr[i]
            int cnt = 0;
            for (int j = i; j < n; j++) {
                if (arr[j] == arr[i])
                    cnt += 1;
            }

            // Check if arr[i] is a majority element
            if (cnt > (n / 3)) {
              
                // Add arr[i] only if it is not already
                // present in the result
                if (res.Count == 0 || arr[i] != res[0]) {
                    res.Add(arr[i]);
                }
            }

            // If we have found two majority elements, 
            // we can stop our search
            if (res.Count == 2) {
                if (res[0] > res[1]) {
                    int temp = res[0];
                    res[0] = res[1];
                    res[1] = temp;
                }
                break;
            }
        }

        return res;
    }

    static void Main(string[] args) {
        int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
        List<int> res = findMajority(arr);
        foreach (int ele in res)
            Console.Write(ele + " ");
    }
}
JavaScript
// JavaScript program to find Majority elements in an array
// using nested loops

function findMajority(arr) {
    const n = arr.length;
    const res = [];

    for (let i = 0; i < n; i++) {
        
        // Count the frequency of arr[i]
        let cnt = 0;
        for (let j = i; j < n; j++) {
            if (arr[j] === arr[i]) {
                cnt += 1;
            }
        }
      
        // Check if arr[i] is a majority element
        if (cnt > (n / 3)) {
          
            // Add arr[i] only if it is not already
            // present in the result
            if (res.length === 0 || arr[i] !== res[0]) {
                res.push(arr[i]);
            }
        }
      
        // If we have found two majority elements, 
        // we can stop our search
        if (res.length === 2) {
            if (res[0] > res[1]) {
                [res[0], res[1]] = [res[1], res[0]];
            }
            break;
        }
    }

    return res;
}

const arr = [2, 2, 3, 1, 3, 2, 1, 1];
const res = findMajority(arr);
console.log(res.join(" "));

Output
1 2 

[Better Approach] Using Hash Map or Dictionary – O(n) Time and O(n) Space

The idea is to use a hash map or dictionary to count the frequency of each element in the array. After counting, iterate over the hash map and if the frequency of any element is greater than (n/3), push it into the result. Finally, the majority elements are returned after sorting.

C++
// C++ program for finding out majority element in an array
// using hash map

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

// Function to find Majority element in an array
vector<int> findMajority(vector<int> &arr) {
    int n = arr.size();
    unordered_map<int, int> freq;
    vector<int> res;

    // find frequency of each number
    for (int ele : arr)
        freq[ele]++;

    // Iterate over each key-value pair in the hash map
    for (auto it : freq) {
        int ele = it.first;
        int cnt = it.second;

        // Add the element to the result, if its frequency
        // if greater than floor(n/3)
        if (cnt > n / 3)
            res.push_back(ele);
    }

    if (res.size() == 2 && res[0] > res[1])
        swap(res[0], res[1]);
    return res;
}

int main() {

    vector<int> arr = {2, 2, 3, 1, 3, 2, 1, 1};
    vector<int> res = findMajority(arr);
    for (auto ele : res) {
        cout << ele << " ";
    }
    return 0;
}
Java
// Java program for finding out majority element in an array
// using hash map

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

class GfG {
    
    // Function to find Majority element in an array
    static List<Integer> findMajority(int[] arr) {
        int n = arr.length;
        HashMap<Integer, Integer> freq = new HashMap<>();
        List<Integer> res = new ArrayList<>();
        
        // find frequency of each number
        for (int ele : arr)
            freq.put(ele, freq.getOrDefault(ele, 0) + 1);
      
        // Iterate over each key-value pair in the hash map
        for (Map.Entry<Integer, Integer> it : freq.entrySet()) {
            int ele = it.getKey();
            int cnt = it.getValue();
          
            // Add the element to the result, if its frequency
        	// if greater than floor(n/3)
            if (cnt > n / 3)
                res.add(ele);
        }
      
        if (res.size() == 2 && res.get(0) > res.get(1)) {
            int temp = res.get(0);
            res.set(0, res.get(1));
            res.set(1, temp);
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {2, 2, 3, 1, 3, 2, 1, 1};
        List<Integer> res = findMajority(arr);
        for (int ele : res) {
            System.out.print(ele + " ");
        }
    }
}
Python
# Python program for finding out majority element in an array
# using hash map

def findMajority(arr):
    n = len(arr)
    freq = {}
    res = []

    # find frequency of each number
    for ele in arr:
        freq[ele] = freq.get(ele, 0) + 1

    # Iterate over each key-value pair in the hash map
    for ele, cnt in freq.items():
        
        # Add the element to the result, if its frequency
        # is greater than floor(n/3)
        if cnt > n // 3:
            res.append(ele)

    if len(res) == 2 and res[0] > res[1]:
        res[0], res[1] = res[1], res[0]
    return res

if __name__ == "__main__":
    arr = [2, 2, 3, 1, 3, 2, 1, 1]
    res = findMajority(arr)
    for ele in res:
        print(ele, end=" ")
C#
// C# program for finding out majority element in an array
// using hash map

using System;
using System.Collections.Generic;

class GfG {
    
    // Function to find Majority element in an array
    static List<int> findMajority(int[] arr) {
        int n = arr.Length;
        Dictionary<int, int> freq = new Dictionary<int, int>();
        List<int> res = new List<int>();

        // find frequency of each number
        foreach (int ele in arr) {
            if (freq.ContainsKey(ele))
                freq[ele]++;
            else
                freq[ele] = 1;
        }

        // Iterate over each key-value pair in the hash map
        foreach (var it in freq) {
            int ele = it.Key;
            int cnt = it.Value;

            // Add the element to the result, if its frequency
            // is greater than floor(n/3)
            if (cnt > n / 3)
                res.Add(ele);
        }

        if (res.Count == 2 && res[0] > res[1]) {
            int temp = res[0];
            res[0] = res[1];
            res[1] = temp;
        }
        return res;
    }

    static void Main() {
        int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
        List<int> res = findMajority(arr);
        foreach (int ele in res) {
            Console.Write(ele + " ");
        }
    }
}
JavaScript
// JavaScript program for finding out majority element in an array
// using hash map

function findMajority(arr) {
    const n = arr.length;
    const freq = {};
    const res = [];

    // find frequency of each number
    for (const ele of arr) {
        freq[ele] = (freq[ele] || 0) + 1;
    }

    // Iterate over each key-value pair in the hash map
    for (const it in freq) {
        const ele = Number(it);
        const cnt = freq[it];

        // Add the element to the result, if its frequency
        // is greater than floor(n/3)
        if (cnt > Math.floor(n / 3)) {
            res.push(ele);
        }
    }

    if (res.length === 2 && res[0] > res[1]) {
        [res[0], res[1]] = [res[1], res[0]];
    }
    return res;
}

const arr = [2, 2, 3, 1, 3, 2, 1, 1];
const res = findMajority(arr);
console.log(res.join(" "));

Output
1 2 

[Expected Approach] Boyer-Moore’s Voting Algorithm – O(n) Time and O(1) Space

The idea is based on the observation that there can be at most two majority elements, which appear more than n/3 times. so we can use Boyer-Moore’s Voting algorithm. As we iterate the array, We identify potential majority elements by keeping track of two candidates and their respective counts.

Steps:

  • Initialize two variables ele1 = -1 and ele2 = -1, for candidates and two variables cnt1 = 0 and cnt2 = 0, for counting.
  • In each iteration,
    • If an element is equal to any candidate, update that candidate’s count.
    • If count of a candidate reaches zero then replace that candidate with current element.
    • If neither candidate matches and both counts are non zero, decrement the counts.
  • After this, in second pass we check if the chosen candidates appear more than n/3 times in the array. If they do then include them in result array.

Since any element than appears more than floor(n/3) times, will dominate over elements that appear less frequently. Whenever we encounter a different element, we decrement the count of both the candidates. This maintains at most two candidates in the array.


C++
// C++ program for finding the majority element in an array
// using Moore’s Voting algorithm

#include <iostream>
#include <vector>
#include <algorithm>
#include <limits.h>
using namespace std;

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

    // Initialize two candidates and their counts
    int ele1 = -1, ele2 = -1, cnt1 = 0, cnt2 = 0;

    for (int ele : arr) {
      
        // Increment count for candidate 1
        if (ele1 == ele) {
            cnt1++;
        }
      
        // Increment count for candidate 2
        else if (ele2 == ele) {
            cnt2++;
        }
      
        // New candidate 1 if count is zero
        else if (cnt1 == 0) {
            ele1 = ele;
            cnt1++;
        }
      
        // New candidate 2 if count is zero
        else if (cnt2 == 0) {
            ele2 = ele;
            cnt2++;
        }
      
        // Decrease counts if neither candidate
        else {
            cnt1--;
            cnt2--;
        }
    }

    vector<int> res;
    cnt1 = 0;
    cnt2 = 0;

    // Count the occurrences of candidates
    for (int ele : arr) {
        if (ele1 == ele) cnt1++;
        if (ele2 == ele) cnt2++;
    }

    // Add to result if they are majority elements
    if (cnt1 > n / 3) res.push_back(ele1);
    if (cnt2 > n / 3 && ele1 != ele2) res.push_back(ele2);
    
    if(res.size() == 2 && res[0] > res[1])
        swap(res[0], res[1]);
    return res;
}

int main() {
  
    vector<int> arr = {2, 2, 3, 1, 3, 2, 1, 1};
    vector<int> res = findMajority(arr);
    for (int ele : res) {
        cout << ele << " ";
    }
    return 0;
}
C
// C program for finding the majority element in an array
// using Moore’s Voting algorithm

#include <stdio.h>
#include <limits.h>

void findMajority(int arr[], int n, int *res, int *resSize) {
    
    // Initialize two candidates and their counts
    int ele1 = -1, ele2 = -1, cnt1 = 0, cnt2 = 0;

    for (int i = 0; i < n; i++) {
        int ele = arr[i];

        // Increment count for candidate 1
        if (ele1 == ele) {
            cnt1++;
        }
        
        // Increment count for candidate 2
        else if (ele2 == ele) {
            cnt2++;
        }
        
        // New candidate 1 if count is zero
        else if (cnt1 == 0) {
            ele1 = ele;
            cnt1++;
        }
        
        // New candidate 2 if count is zero
        else if (cnt2 == 0) {
            ele2 = ele;
            cnt2++;
        }
        
        // Decrease counts if neither candidate
        else {
            cnt1--;
            cnt2--;
        }
    }

    cnt1 = 0;
    cnt2 = 0;

    // Count the occurrences of candidates
    for (int i = 0; i < n; i++) {
        int ele = arr[i];
        if (ele1 == ele) cnt1++;
        if (ele2 == ele) cnt2++;
    }

    // Add to result if they are majority elements
    *resSize = 0;
    if (cnt1 > n / 3) res[(*resSize)++] = ele1;
    if (cnt2 > n / 3 && ele1 != ele2) res[(*resSize)++] = ele2;

    // Sort the result if there are two elements
    if (*resSize == 2 && res[0] > res[1]) {
        int temp = res[0];
        res[0] = res[1];
        res[1] = temp;
    }
}

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

    findMajority(arr, n, res, &resSize);
    for (int i = 0; i < resSize; i++) {
        printf("%d ", res[i]);
    }
    return 0;
}
Java
// Java program for finding the majority element in an array
// using Moore’s Voting algorithm

import java.util.ArrayList;
import java.util.List;

class GfG {

    // Function to find Majority element in an array
    static List<Integer> findMajority(int[] arr) {
        int n = arr.length;

        // Initialize two candidates and their counts
        int ele1 = -1, ele2 = -1;
        int cnt1 = 0, cnt2 = 0;

        for (int ele : arr) {
          
            // Increment count for candidate 1
            if (ele1 == ele) {
                cnt1++;
            }
          
            // Increment count for candidate 2
            else if (ele2 == ele) {
                cnt2++;
            }
          
            // New candidate 1 if count is zero
            else if (cnt1 == 0) {
                ele1 = ele;
                cnt1++;
            }
          
            // New candidate 2 if count is zero
            else if (cnt2 == 0) {
                ele2 = ele;
                cnt2++;
            }
          
            // Decrease counts if neither candidate
            else {
                cnt1--;
                cnt2--;
            }
        }

        List<Integer> res = new ArrayList<>();
        cnt1 = 0;
        cnt2 = 0;

        // Count the occurrences of candidates
        for (int ele : arr) {
            if (ele1 == ele) cnt1++;
            if (ele2 == ele) cnt2++;
        }

        // Add to result if they are majority elements
        if (cnt1 > n / 3) res.add(ele1);
        if (cnt2 > n / 3 && ele1 != ele2) res.add(ele2);
        
        if (res.size() == 2 && res.get(0) > res.get(1)) {
            int temp = res.get(0);
            res.set(0, res.get(1));
            res.set(1, temp);
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {2, 2, 3, 1, 3, 2, 1, 1};
        List<Integer> res = findMajority(arr);
        for (int ele : res) {
            System.out.print(ele + " ");
        }
    }
}
Python
# Python program for finding the majority element in 
# an array using Moore’s Voting algorithm

def findMajority(arr):
    n = len(arr)

    # Initialize two candidates and their counts
    ele1, ele2 = -1, -1
    cnt1, cnt2 = 0, 0

    for ele in arr:
        # Increment count for candidate 1
        if ele1 == ele:
            cnt1 += 1
        # Increment count for candidate 2
        elif ele2 == ele:
            cnt2 += 1
        # New candidate 1 if count is zero
        elif cnt1 == 0:
            ele1 = ele
            cnt1 += 1
        # New candidate 2 if count is zero
        elif cnt2 == 0:
            ele2 = ele
            cnt2 += 1
        # Decrease counts if neither candidate
        else:
            cnt1 -= 1
            cnt2 -= 1

    res = []
    cnt1, cnt2 = 0, 0

    # Count the occurrences of candidates
    for ele in arr:
        if ele1 == ele:
            cnt1 += 1
        if ele2 == ele:
            cnt2 += 1

    # Add to result if they are majority elements
    if cnt1 > n / 3:
        res.append(ele1)
    if cnt2 > n / 3 and ele1 != ele2:
        res.append(ele2)

    if len(res) == 2 and res[0] > res[1]:
        res[0], res[1] = res[1], res[0]

    return res

if __name__ == "__main__":
    arr = [2, 2, 3, 1, 3, 2, 1, 1]
    res = findMajority(arr)
    for ele in res:
        print(ele, end=" ")
C#
// C# program for finding the majority element in an array
// using Moore’s Voting algorithm

using System;
using System.Collections.Generic;

class GfG { 
    
    // Function to find Majority element in an array
    static List<int> FindMajority(int[] arr) {
        int n = arr.Length;

        // Initialize two candidates and their counts
        int ele1 = -1, ele2 = -1, cnt1 = 0, cnt2 = 0;

        foreach (int ele in arr) {
            
            // Increment count for candidate 1
            if (ele1 == ele) {
                cnt1++;
            }
            
            // Increment count for candidate 2
            else if (ele2 == ele) {
                cnt2++;
            }
            
            // New candidate 1 if count is zero
            else if (cnt1 == 0) {
                ele1 = ele;
                cnt1++;
            }
            
            // New candidate 2 if count is zero
            else if (cnt2 == 0) {
                ele2 = ele;
                cnt2++;
            }
           
            // Decrease counts if neither candidate
            else {
                cnt1--;
                cnt2--;
            }
        }

        List<int> res = new List<int>();
        cnt1 = 0;
        cnt2 = 0;

        // Count the occurrences of candidates
        foreach (int ele in arr) {
            if (ele1 == ele) cnt1++;
            if (ele2 == ele) cnt2++;
        }

        // Add to result if they are majority elements
        if (cnt1 > n / 3) res.Add(ele1);
        if (cnt2 > n / 3 && ele1 != ele2) res.Add(ele2);

        if (res.Count == 2 && res[0] > res[1]) {
            int temp = res[0];
            res[0] = res[1];
            res[1] = temp;
        }
        return res;
    }

    static void Main() {
        int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
        List<int> res = FindMajority(arr);
        foreach (int ele in res) {
            Console.Write(ele + " ");
        }
    }
}
JavaScript
// JavaScript program for finding the majority element in an array
// using Moore’s Voting algorithm

function findMajority(arr) {
    const n = arr.length;

    // Initialize two candidates and their counts
    let ele1 = -1, ele2 = -1;
    let cnt1 = 0, cnt2 = 0;

    for (let ele of arr) {
        
        // Increment count for candidate 1
        if (ele1 === ele) {
            cnt1++;
        }
        
        // Increment count for candidate 2
        else if (ele2 === ele) {
            cnt2++;
        }
        
        // New candidate 1 if count is zero
        else if (cnt1 === 0) {
            ele1 = ele;
            cnt1++;
        }
        
        // New candidate 2 if count is zero
        else if (cnt2 === 0) {
            ele2 = ele;
            cnt2++;
        }
        
        // Decrease counts if neither candidate
        else {
            cnt1--;
            cnt2--;
        }
    }

    const res = [];
    cnt1 = 0;
    cnt2 = 0;

    // Count the occurrences of candidates
    for (let ele of arr) {
        if (ele1 === ele) cnt1++;
        if (ele2 === ele) cnt2++;
    }

    // Add to result if they are majority elements
    if (cnt1 > n / 3) res.push(ele1);
    if (cnt2 > n / 3 && ele1 != ele2) res.push(ele2);
    
    if (res.length === 2 && res[0] > res[1]) {
        [res[0], res[1]] = [res[1], res[0]];
    }
    return res;
}

const arr = [2, 2, 3, 1, 3, 2, 1, 1];
const res = findMajority(arr);
console.log(res.join(" "));

Output
1 2 




Next Article

Similar Reads

three90RightbarBannerImg