Open In App

Find all array elements occurring more than ⌊N/3⌋ times

Last Updated : 11 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
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.

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


Python3




# Python3 program to find Majority element in an array
 
# Function to find Majority element
# in an array
def findMajority(arr,  n):
    flag = 0
    for i in range(n):
        count = 0
        for j in range(i, n):
            if (arr[i] == arr[j]):
                count+=1
  
        # If count is greater than n/3 means
        # current element is majority element
        if (count > int(n / 3)):
            print(arr[i], end = " ")
            flag = 1
      
    # If flag is 0 means there is no
    # majority element is present
    if (flag == 0):
        print("No Majority Element")
 
arr = [ 2, 2, 3, 1, 3, 2, 1, 1 ]
n = len(arr)
  
# Function calling
findMajority(arr, n)
 
# This code is contributed by mukesh07.


C#




// C# program to find Majority
// element in an array
using System;
using System.Collections.Generic;
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) {
                Console.Write(arr[i] + " ");
                flag = 1;
            }
        }
   
        // if flag is 0 means there is no
          // majority element is present
        if (flag == 0)
            Console.Write("No Majority Element");
    
    }
     
  static void Main() {
    int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
    int n = arr.Length;
 
    // Function calling
    findMajority(arr, n); 
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




<script>
 
// Javascript program to find Majority
// element in an array
  
// Function to find Majority element
// in an array
function findMajority(arr,  n)
{
    var flag = 0;
    for(var i = 0; i < n; i++)
    {
        var count = 0;
        for(var 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)
        {
            document.write(arr[i] + " ");
            flag = 1;
        }
    }
     
    // If flag is 0 means there is no
    // majority element is present
    if (flag == 0)
    {
        document.write("No Majority Element");
    }
}
 
// Driver code
var arr = [ 2, 2, 3, 1, 3, 2, 1, 1 ];
var n = arr.length;
 
// Function calling
findMajority(arr, n);
 
// This code is contributed by bunnyram19
 
</script>


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


Python3




# Python3 program for finding out majority element in an array
def findMajority(arr, size):
    m = {}
    for i in range(size):
        if arr[i] in m:
            m[arr[i]] += 1
        else:
            m[arr[i]] = 1
    flag = 0
    for i in sorted(m):
        if m[i] > int(size / 3):
            flag =1
            print(i, end = " ")
    if flag == 0:
        print("No Majority element")
 
arr = [ 2, 2, 3, 1, 3, 2, 1, 1]
n = len(arr)
   
# Function calling
findMajority(arr, n)
 
# This code is contributed by rameshtravel07.


C#




/* C# program for finding out majority
element in an array */
using System;
using System.Collections.Generic;
class GFG {
     
    static void findMajority(int[] arr, int size)
    {
        Dictionary<int, int> m = new Dictionary<int, int>();
        for(int i = 0; i < size; i++)
        {
            if(m.ContainsKey(arr[i]))
            {
                m[arr[i]]++;
            }
            else{
                m[arr[i]] = 1;
            }
        }
        int flag = 0;
        List<int> ans = new List<int>();
        foreach(KeyValuePair<int, int> i in m)
        {
            if(i.Value > size / 3)
            {
                flag =1;
                ans.Add(i.Key);
            }
        }
        if(ans.Count > 0)
        {
            ans.Sort();
            for(int i = 0; i < ans.Count; i++)
            {
                Console.Write(ans[i] + " ");
            }
        }
        if(flag == 0)
            Console.WriteLine("No Majority element");
    }
 
  static void Main() {
    int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1};
    int n = arr.Length;
       
    // Function calling
    findMajority(arr, n);
  }
}
 
// This code is contributed by decode2207,


Javascript




<script>
 
/* JavaScript program for finding out majority
element in an array */
function findMajority(arr, size)
{
    let m = new Map();
    for(let i = 0; i < size; i++)
    {
        if(m.has(arr[i]) == true){
             m.set(arr[i], m.get(arr[i]) + 1);
        }
        else m.set(arr[i], 1);
    }
    let flag = 0;
    for(let [key, value] of m)
    {
        if(value > size / 3)
        {
            flag = 1;
            document.write(key, " ");
        }
    }
    if(flag == 0)
        document.write("No Majority element","</br>");
}
  
// Driver code
let arr = [ 2, 2, 3, 1, 3, 2, 1, 1 ];
let n = arr.length;
      
// Function calling
findMajority(arr, n);
 
// This code is contributed by shinjanpatra
 
</script>


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


Python3




# Python3 program to find Majority
# element in an array
 
# Function to find Majority element
# in an array
def findMajority(arr, n):
    count1 = 0
    count2 = 0
    first = 2147483647
    second = 2147483647
    flag = 0
    for i in range(n):
       
      # if this element is previously seen,
      # increment count1.
      if first == arr[i]:
        count1 += 1
         
      # if this element is previously seen,
      # increment count2.
      elif second == arr[i]:
        count2 += 1
      elif count1 == 0:
        count1 += 1
        first = arr[i]
      elif count2 == 0:
        count2 += 1
        second = arr[i]
     
      # if current element is different from
      # both the previously seen variables,
      # decrement both the counts.
      else:
        count1 -= 1
        count2 -= 1
     
    count1 = 0
    count2 = 0
     
    # Again traverse the array and find the
    # actual counts.
    for i in range(n):
      if arr[i] == first:
        count1 += 1
      elif arr[i] == second:
        count2 += 1
     
    if count1 > int(n / 3):
      print(first, end = " ")
      flag = 1
    if count2 > int(n / 3):
      print(second, end = " ")
      flag = 1
    if flag == 0:
      print("No Majority Element")
 
arr = [ 2, 2, 3, 1, 3, 2, 1, 1 ]
n = len(arr)
 
# Function calling
findMajority(arr, n)
 
# This code is contributed by divyesh072019.


C#




// C# program to find if any element appears
// more than n/3
using System;
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 = Int32.MinValue;
        int second = Int32.MaxValue;
      
        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){
            Console.Write(first+" ");
              flag=1;
        }
        if (count2 > n / 3){
            Console.Write(second+" ");
              flag=1;
        }
          if(flag==0)
           Console.Write("No Majority Element");
    }
     
  static void Main() {
    int[] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
    int n = arr.Length;
    findMajority(arr,n);
  }
}
 
// This code is contributed by suresh07.


Javascript




<script>
 
      // JavaScript program to find Majority
      // element in an array
       
      // Function to find Majority element
      // in an array
      function findMajority(arr, n) {
        var count1 = 0,
          count2 = 0;
        var first = 2147483647,
          second = 2147483647;
        var flag = 0;
        for (var 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 (var i = 0; i < n; i++) {
          if (arr[i] === first) count1++;
          else if (arr[i] === second) count2++;
        }
 
        if (count1 > n / 3) {
          document.write(first + " ");
          flag = 1;
        }
        if (count2 > n / 3) {
          document.write(second + " ");
          flag = 1;
        }
        if (flag === 0) {
          document.write("No Majority Element" + "<br>");
        }
      }
 
      var arr = [2, 2, 3, 1, 3, 2, 1, 1];
      var n = arr.length;
 
      // Function calling
      findMajority(arr, n);
       
</script>


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:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the majority
// element by Divide and Conquer
vector<int> divideAndConquer(int lo, int hi, int a[])
{
    if (lo == hi) {
        vector<int> ans{ a[lo] };
        return ans;
    }
 
    // Find mid
    int mid = lo + (hi - lo) / 2;
 
    // Call to the left half
    vector<int> left = divideAndConquer(lo, mid, a);
 
    // Call to the right half
    vector<int> right = divideAndConquer(mid + 1, hi, a);
    //  Stores the result
    vector<int> result;
    for (auto it : left) {
        for (auto itr : right) {
            bool flag = 0;
            if (it == itr) {
                flag = 1;
                break;
            }
            if (!flag)
                result.push_back(it);
        }
    }
 
    for (auto it : right)
        result.push_back(it);
 
    // Stores all majority elements
    vector<int> ans;
 
    for (auto it : result) {
        int count = 0;
 
        // Count of elements that
        // occurs most
        for (int i = lo; i <= hi; i++)
            if (a[i] == it)
                count += 1;
 
        // If the number is a
        // majority element
        if (count > (hi - lo + 1) / 3)
            ans.push_back(it);
    }
 
    // Return the list of element
    return ans;
}
 
//  Function to find all elements that
//  occurs >= N/3 times in the array
void majorityElement(int a[], int n)
{
 
    // If array is empty return
    // empty list
    if (n == 0)
        return;
   
    // Function Call
    vector<int> ans = divideAndConquer(0, n - 1, a);
    for (auto it : ans) {
        cout << it << " ";
    }
}
 
// Driver Code
int main()
{
 
    // Given array a[]
    int a[] = { 7, 7, 7, 3, 4, 4, 4, 6 };
 
    // Function Call
    majorityElement(a, 8);
}
 
// This code is contributed by garg28harsh.


Java




// Java program for the above approach
 
import java.util.*;
 
class GFG {
    // Function to find the majority
    // element by Divide and Conquer
    static ArrayList<Integer>
    divideAndConquer(int lo, int hi, int[] a)
    {
        if (lo == hi) {
            ArrayList<Integer> ans_
                = new ArrayList<Integer>();
            ans_.add(a[lo]);
            return ans_;
        }
 
        // Find mid
        int mid = lo + (hi - lo) / 2;
 
        // Call to the left half
        ArrayList<Integer> left
            = divideAndConquer(lo, mid, a);
 
        // Call to the right half
        ArrayList<Integer> right
            = divideAndConquer(mid + 1, hi, a);
        //  Stores the result
        ArrayList<Integer> result
            = new ArrayList<Integer>();
        for (var it : left) {
            for (var itr : right) {
                boolean flag = false;
                if (it == itr) {
                    flag = true;
                    break;
                }
                if (!flag)
                    result.add(it);
            }
        }
 
        for (var it : right)
            result.add(it);
 
        // Stores all majority elements
        ArrayList<Integer> ans = new ArrayList<Integer>();
 
        for (var it : result) {
            int count = 0;
 
            // Count of elements that
            // occurs most
            for (int i = lo; i <= hi; i++)
                if (a[i] == it)
                    count += 1;
 
            // If the number is a
            // majority element
            if (count > (hi - lo + 1) / 3)
                ans.add(it);
        }
 
        // Return the list of element
        return ans;
    }
 
    //  Function to find all elements that
    //  occurs >= N/3 times:the array
    static void majorityElement(int[] a, int n)
    {
 
        // If array is empty return
        // empty list
        if (n == 0)
            return;
 
        // Function Call
        ArrayList<Integer> res
            = divideAndConquer(0, n - 1, a);
        for (var it : res) {
            System.out.print(it + " ");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array a[]
        int[] a = { 7, 7, 7, 3, 4, 4, 4, 6 };
 
        // Function Call
        majorityElement(a, 8);
    }
}
 
// This code is contributed by phasing17.


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)


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
  // Function to find the majority
  // element by Divide and Conquer
  static List<int> divideAndConquer(int lo, int hi, int[] a)
  {
    if (lo == hi) {
      List<int> ans_ = new List<int>();
      ans_.Add(a[lo]);
      return ans_;
    }
 
    // Find mid
    int mid = lo + (hi - lo) / 2;
 
    // Call to the left half
    List<int> left = divideAndConquer(lo, mid, a);
 
    // Call to the right half
    List<int> right = divideAndConquer(mid + 1, hi, a);
    //  Stores the result
    List<int> result = new List<int>();
    foreach (var it in left) {
      foreach (var itr in right) {
        bool flag = false;
        if (it == itr) {
          flag = true;
          break;
        }
        if (!flag)
          result.Add(it);
      }
    }
 
    foreach (var it in right)
      result.Add(it);
 
    // Stores all majority elements
    List<int> ans = new List<int>();
 
    foreach (var it in result) {
      int count = 0;
 
      // Count of elements that
      // occurs most
      for (int i = lo; i <= hi; i++)
        if (a[i] == it)
          count += 1;
 
      // If the number is a
      // majority element
      if (count > (hi - lo + 1) / 3)
        ans.Add(it);
    }
 
    // Return the list of element
    return ans;
  }
 
  //  Function to find all elements that
  //  occurs >= N/3 times in the array
  static void majorityElement(int[] a, int n)
  {
 
    // If array is empty return
    // empty list
    if (n == 0)
      return;
 
    // Function Call
    List<int> res = divideAndConquer(0, n - 1, a);
    foreach (var it in res) {
      Console.Write(it + " ");
    }
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Given array a[]
    int[] a = { 7, 7, 7, 3, 4, 4, 4, 6 };
 
    // Function Call
    majorityElement(a, 8);
  }
}
 
// This code is contributed by phasing17.


Javascript




// Javascript program for the above approach
 
// Function to find the majority
// element by Divide and Conquer
function divideAndConquer( lo,  hi, a)
{
    if (lo == hi) {
        let ans=[];
        ans.push(a[hi]);
        return ans;
    }
 
    // Find mid
    let mid = Math.round( (hi + lo) / 2)-1;
     
    // Call to the left half
    let left = divideAndConquer(lo, mid, a);
 
    // Call to the right half
    let right = divideAndConquer(mid + 1, hi, a);
     
    //  Stores the result
    let result = [];
    for (let i = 0; i < left.length; i++) {
        let it = left[i];
        for (let j = 0; j < right.length; j++) {
            let itr = right[j];
            let flag = false;
            if (it == itr) {
                flag = 1;
                break;
            }
            if (flag == false)
                result.push(it);
        }
    }
 
    for (let i = 0; i < right.length; i++)
        result.push(right[i]);
 
    // Stores all majority elements
    let ans = [];
 
    for (let i = 0; i < result.length; i++) {
        let it = result[i];
        let count = 0;
 
        // Count of elements that
        // occurs most
        for (let i = lo; i <= hi; i++)
            if (a[i] == it)
                count += 1;
 
        // If the number is a
        // majority element
        if (count > (hi - lo + 1) / 3)
            ans.push(it);
    }
 
    // Return the list of element
    return ans;
}
 
//  Function to find all elements that
//  occurs >= N/3 times in the array
function majorityElement(a, n)
{
 
    // If array is empty return
    // empty list
    if (n == 0)
        return;
   
    // Function Call
    let ans = divideAndConquer(0, n - 1, a);
    console.log(ans);
}
 
// Driver Code
 
    // Given array a[]
    let a = [ 7, 7, 7, 3, 4, 4, 4, 6 ];
 
    // Function Call
    majorityElement(a, 8);
     
    // This code is contributed by garg28harsh.


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:

C++




#include <iostream>
#include <unordered_map>
#include <vector>
 
using namespace std;
 
// Function to find the number of array
// elements with frequency more than n/3 times
void printElements(int arr[], int n)
{
    // Calculating n/3
    int x = n / 3;
     
    // Counting frequency of every element using unordered_map
    unordered_map<int, int> mp;
     
    for (int i = 0; i < n; i++) {
        if (mp.find(arr[i]) == mp.end()) {
            mp[arr[i]] = 1;
        } else {
            mp[arr[i]]++;
        }
    }
     
    vector<int> result;
    for (auto entry : mp) {
        if (entry.second > x) {
            result.push_back(entry.first);
        }
    }
 
    // Printing the elements with frequency more than n/3 times
    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << " ";
    }
}
 
// Driver code
int main()
{
    int arr[] = { 7, 7, 7, 3, 4, 4, 4, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printElements(arr, n);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
public class Main {
 
  // Function to find the number of array
  // elements with frequency more than n/3 times
  public static void printElements(int[] arr, int n)
  {
    // Calculating n/3
    int x = n / 3;
 
    // Counting frequency of every element using Counter
    Map<Integer, Integer> mp = new HashMap<>();
 
    for (int i = 0; i < arr.length; i++) {
      if (!mp.containsKey(arr[i])) {
        mp.put(arr[i], 1);
      }
      else {
        mp.put(arr[i], mp.get(arr[i]) + 1);
      }
    }
 
    for (Map.Entry<Integer, Integer> entry :
         mp.entrySet()) {
      if (entry.getValue() > x) {
        System.out.print(entry.getKey() + " ");
      }
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] arr = { 7, 7, 7, 3, 4, 4, 4, 6 };
    int n = arr.length;
    printElements(arr, n);
  }
}


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


C#




using System;
using System.Collections.Generic;
 
public class MainClass
{
// Function to find the number of array
// elements with frequency more than n/3 times
    public static void PrintElements(int[] arr, int n)
    {
// Calculating n/3
        int x = n / 3;
 
// Counting frequency of every element using Dictionary
        Dictionary<int, int> dict = new Dictionary<int, int>();
 
        for (int i = 0; i < arr.Length; i++)
        {
            if (!dict.ContainsKey(arr[i]))
            {
                dict.Add(arr[i], 1);
            }
            else
            {
                dict[arr[i]] += 1;
            }
        }
 
        foreach (KeyValuePair<int, int> kvp in dict)
        {
            if (kvp.Value > x)
            {
                Console.Write(kvp.Key + " ");
            }
        }
    }
 
// Driver code
    public static void Main()
    {
        int[] arr = { 7, 7, 7, 3, 4, 4, 4, 6 };
        int n = arr.Length;
        PrintElements(arr, n);
    }
}


Javascript




// Javascript program for the above approach
function printElements(arr, n) {
    // Calculating n/3
    let x = Math.floor(n / 3);
 
    // Counting frequency of every element using Counter
    let mp = new Map();
    for (let i = 0; i < n; i++) {
        if (mp.has(arr[i])) {
            mp.set(arr[i], mp.get(arr[i]) + 1);
        } else {
            mp.set(arr[i], 1);
        }
    }
 
    // Traverse the map and print all
    // the elements with occurrence atleast n/3 times
    for (let [key, value] of mp) {
        if (value > x) {
            console.log(key, end = " ");
        }
    }
}
 
// Driver code
let arr = [7, 7, 7, 3, 4, 4, 4, 6];
 
// Size of array
let n = arr.length;
 
// Function Call
printElements(arr, n);


Output

7 4 

Time Complexity: O(N)

Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads