Skip to content
Related Articles

Related Articles

Find all array elements occurring more than ⌊N/3⌋ times
  • Difficulty Level : Easy
  • Last Updated : 14 May, 2021

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.

Examples:

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

Input: arr[] = {7, 7, 7, 3, 4, 4, 4, 5}
Output: 4 7
Explanation:
The frequency of 7 and 4 in the array is 3, which is more than N/3( 8/3 = 2).

Method 1:

Approach: The basic solution is to have two loops and keep track of the maximum count for all different elements. If maximum count becomes greater than n/3 then print it. If the maximum count doesn’t become more than n/3 after the traversal of array then the majority element doesn’t exists.



C++




// C++ program to find Majority
// element in an array
#include <bits/stdc++.h>
using namespace std;
  
// Function to find Majority element
// in an array
void findMajority(int arr[], int n) {
     
    int flag = 0;
    for (int i = 0; i < n; i++) {
        int count = 0;
        for (int j = i; j < n; j++) {
            if (arr[i] == arr[j]) {
                count++;
            }
        }
        if (count > (n / 3)) {
            cout << arr[i] << " ";
            flag = 1;
        }
    }
    if (!flag)
        cout << "No Majority Element" << endl;
}
int main() {
 
    int arr[] = { 2, 2, 3, 1, 3, 2, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function calling
    findMajority(arr, n);
    return 0;
}
 
// This code is contributed by Aman Chowdhury

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 flag=0;
        for (int i = 0; i < n; i++) {
            int count = 0;
            for (int j = i; j < n; j++) {
                if (arr[i] == arr[j])
                    count++;
            }
  
            // if count is greater than n/3 means
              // current element is majority element
            if (count > n/3) {
                System.out.print(arr[i]+" ");
                  flag=1;
            }
        }
  
        // if flag is 0 means there is no
          // majority element is present
        if (flag==0)
            System.out.println("No Majority Element");
   
    }
  
    public static void main (String[] args) {
        int arr[] = { 2, 2, 3, 1, 3, 2, 1, 1 };
        int n = arr.length;
  
        // Function calling
        findMajority(arr, n);
    }
}
 
// This code is contributed by Aman Chowdhury
Output
2 1 

Complexity Analysis: 

  • Time Complexity: O(n*n)                                                                                                                                                      A nested loop is needed where both the loops traverse the array from start to end, so the time complexity is O(n^2).
  • Auxiliary Space:  O(1)                                                                                                                                                          As no extra space is required for any operation so the space complexity is constant.

Method 2 (Using Hashmap):

  • Approach: This method is somewhat similar to Moore voting algorithm in terms of time complexity, but in this case, there is no need for the second step of Moore voting algorithm. But as usual, here space complexity becomes O(n).  

          In Hashmap(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). 

C++




/* C++ program for finding out majority
element in an array */
#include <bits/stdc++.h>
using namespace std;
  
void findMajority(int arr[], int size)
{
    unordered_map<int, int> m;
    for(int i = 0; i < size; i++)
        m[arr[i]]++;
    int flag = 0;
    for(auto i : m)
    {
        if(i.second > size / 3)
        {
            flag =1;
            cout << i.first << " ";
        }
    }
    if(flag == 0)
        cout << "No Majority element" << endl;
}
  
// Driver code
int main()
{
    int arr[] = { 2, 2, 3, 1, 3, 2, 1, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
      
    // Function calling
    findMajority(arr, n);
  
    return 0;
}
 
// This code is contributed by Aman Chowdhury

Java




import java.util.HashMap;
 
/* Program for finding out majority element in an array */
 
class MajorityElement
{
    private static void findMajority(int[] arr)
    {
        HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
        int flag=0;
        for(int i = 0; i < arr.length; i++) {
            if (map.containsKey(arr[i])) {
                    int count = map.get(arr[i]) +1;
                    if (count > arr.length /3) {
                        System.out.print(arr[i]+" ");
                          flag=1;
                    } else
                        map.put(arr[i], count);
 
            }
            else
                map.put(arr[i],1);
            }
              if(flag==0)
                System.out.println(" No Majority element");
    }
 
 
    /* Driver program to test the above functions */
    public static void main(String[] args)
    {
        int a[] = new int[]{2, 2, 3, 1, 3, 2, 1, 1};
         
        findMajority(a);
    }
}
 
// This code is contributed by Aman Chowdhury
Output
1 2 

Complexity Analysis:

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

Method 3 (Moore’s Voting algorithm):

The idea is based on Moore’s Voting algorithm.  We first find two candidates. Then we check if any of these two candidates is actually a majority. Below is the solution for above approach. 



C++




// C++ program to find Majority
// element in an array
#include <bits/stdc++.h>
using namespace std;
  
// Function to find Majority element
// in an array
void findMajority(int arr[], int n){
      int count1 = 0, count2 = 0;
    int first=INT_MAX, second=INT_MAX;
    int flag=0;
    for (int i = 0; i < n; i++) {
  
        // if this element is previously seen,
        // increment count1.
        if (first == arr[i])
            count1++;
  
        // if this element is previously seen,
        // increment count2.
        else if (second == arr[i])
            count2++;
      
        else if (count1 == 0) {
            count1++;
            first = arr[i];
        }
  
        else if (count2 == 0) {
            count2++;
            second = arr[i];
        }
  
        // if current element is different from
        // both the previously seen variables,
        // decrement both the counts.
        else {
            count1--;
            count2--;
        }
    }
  
    count1 = 0;
    count2 = 0;
  
    // Again traverse the array and find the
    // actual counts.
    for (int i = 0; i < n; i++) {
        if (arr[i] == first)
            count1++;
  
        else if (arr[i] == second)
            count2++;
    }
      
    if (count1 > n / 3){
        cout << first << " ";
          flag=1;
    }
    if (count2 > n / 3){
        cout << second << " ";
          flag=1;
    }
      if(flag==0){
          cout << "No Majority Element" << endl;
    }
}
   
int main() {
 
    int arr[] = { 2, 2, 3, 1, 3, 2, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function calling
    findMajority(arr, n);
  
    return 0;
}
 
// This code is contributed by Aman Chowdhury

Java




// Java program to find if any element appears
// more than n/3.
class GFG {
     
    static void findMajority(int arr[], int n)
    {
        int count1 = 0, count2 = 0;
        int flag=0;
        // take the integers as the maximum
        // value of integer hoping the integer
        // would not be present in the array
        int first = Integer.MIN_VALUE;;
        int second = Integer.MAX_VALUE;
     
        for (int i = 0; i < n; i++) {
     
            // if this element is previously
            // seen, increment count1.
            if (first == arr[i])
                count1++;
     
            // if this element is previously
            // seen, increment count2.
            else if (second == arr[i])
                count2++;
         
            else if (count1 == 0) {
                count1++;
                first = arr[i];
            }
     
            else if (count2 == 0) {
                count2++;
                second = arr[i];
            }
     
            // if current element is different
            // from both the previously seen
            // variables, decrement both the
            // counts.
            else {
                count1--;
                count2--;
            }
        }
     
        count1 = 0;
        count2 = 0;
     
        // Again traverse the array and
        // find the actual counts.
        for (int i = 0; i < n; i++) {
            if (arr[i] == first)
                count1++;
     
            else if (arr[i] == second)
                count2++;
        }
     
        if (count1 > n / 3){
            System.out.print(first+" ");
              flag=1;
        }
        if (count2 > n / 3){
            System.out.print(second+" ");
              flag=1;
        }
          if(flag==0)
           System.out.println("No Majority Element");
    }
     
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 2, 2, 3, 1, 3, 2, 1, 1 };
        int n = arr.length;
        findMajority(arr,n);
         
    }
}
 
// This code is contributed by Aman Chowdhury
Output
2 1 

Complexity Analysis:

  • Time Complexity: O(n)                                                                                                                                                       First pass of the algorithm takes complete traversal over the array contributing to O(n) and another O(n) is consumed in checking if count1 and count2 is greater than floor(n/3) times.
  • Auxiliary Space: O(1)                                                                                                                                                           As no extra space is required so space complexity is constant 

Method 4:

Approach: To solve the problem, the idea is to use Divide and Conquer technique. Follow the steps below to solve the problem:

  1. Initialize a function majorityElement() that will return the count of majority element in the array from any index left to right.
  2. Divide the given array arr[] into two halves and repeatedly pass it to the function majorityElement().
  3. Initialize low and high as 0 and (N – 1) respectively.
  4. Compute the majority element using the following steps:
    • If low = high: Return arr[low] as the majority element.
    • Find the middle index,say mid(= (low + high)/2).
    • Recursively call for both the left and right subarrays as majorityElement(arr, low, mid) and majorityElement(arr, mid + 1, high).
    • After completing the above steps, merge both the subarrays and return the majority element.
  5. Whenever the required majority element is found, append it to the resultant list.
  6. Print all the majority elements stored in the list.

Below is the implementation of the above approach:

Python3




# Python program for the above approach
class Solution:
 
    # Function to find all elements that
    # occurs >= N/3 times in the array
    def majorityElement(self, a):
 
        # If array is empty return
        # empty list
        if not a:
            return []
 
        # Function to find the majority
        # element by Divide and Conquer
        def divideAndConquer(lo, hi):
            if lo == hi:
                return [a[lo]]
 
            # Find mid
            mid = lo + (hi - lo)//2
 
            # Call to the left half
            left = divideAndConquer(lo, mid)
 
            # Call to the right half
            right = divideAndConquer(mid + 1, hi)
 
            # Stores the result
            result = []
            for numbers in left:
                if numbers not in right:
                    result.append(numbers)
 
            result.extend(right)
 
            # Stores all majority elements
            ans = []
 
            for number in result:
                count = 0
 
                # Count of elements that
                # occurs most
                for index in range(lo, hi + 1):
                    if a[index] == number:
                        count += 1
 
                # If the number is a
                # majority element
                if count > (hi - lo + 1)//3:
                    ans.append(number)
 
            # Return the list of element
            return ans
 
        # Function Call
        print(divideAndConquer(0, len(a) - 1))
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given array a[]
    a = [7, 7, 7, 3, 4, 4, 4, 6]
    object = Solution()
 
    # Function Call
    object.majorityElement(a)
Output
[7, 4]

Time Complexity: O(N*log N)
Auxiliary Space: O(log N)

Another Approach: Using Built-in Python functions:

  • Count the frequencies of every element using Counter() function.
  • Traverse the frequency array and print all the elements which occur at more than n/3 times.

Below is the implementation:

Python3




# Python3 program for the above approach
from collections import Counter
 
# Function to find the number of array
# elements with frequency more than n/3 times
def printElements(arr, n):
 
    # Calculating n/3
    x = n//3
 
    # Counting frequency of every element using Counter
    mp = Counter(arr)
     
    # Traverse the map and print all
    # the elements with occurrence atleast n/3 times
    for it in mp:
        if mp[it] > x:
            print(it, end=" ")
 
 
# Driver code
arr = [7, 7, 7, 3, 4, 4, 4, 6]
 
# Size of array
n = len(arr)
 
# Function Call
printElements(arr, n)
 
# This code is contributed by vikkycirus
Output
7 4 

Output:

7 4

Time Complexity: O(N)

Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :